【发布时间】:2019-05-14 03:43:47
【问题描述】:
我正在尝试翻译一个不使用任何循环的递归洪水填充实现。我不断收到堆栈溢出错误,我不知道为什么。我一直在尝试翻译 C++ 代码here。
如何修复我对这段代码的 Java 翻译?
C++原代码:
// A recursive function to replace previous color 'prevC' at '(x, y)'
// and all surrounding pixels of (x, y) with new color 'newC' and
void floodFillUtil(int screen[][N], int x, int y, int prevC, int newC)
{
// Base cases
if (x < 0 || x >= M || y < 0 || y >= N)
return;
if (screen[x][y] != prevC)
return;
// Replace the color at (x, y)
screen[x][y] = newC;
// Recur for north, east, south and west
floodFillUtil(screen, x+1, y, prevC, newC);
floodFillUtil(screen, x-1, y, prevC, newC);
floodFillUtil(screen, x, y+1, prevC, newC);
floodFillUtil(screen, x, y-1, prevC, newC);
}
我的 Java floodFill() 方法:
public void floodFill(int[][] pic, int row, int col, int oldC, int newC) {
// Base Cases
if(row < 0 || col < 0 || row >= pic.length - 1 || col >= pic[row].length - 1) {
return;
}
if(pic[row][col] != oldC) {
return;
}
// recursion
floodFill(pic, row++, col, oldC, newC);
floodFill(pic, row--, col, oldC, newC);
floodFill(pic, row, col++, oldC, newC);
floodFill(pic, row, col--, oldC, newC);
}
【问题讨论】:
-
Java 代码中没有
screen[x][y] = newC;的等价物 -
@TheDark 对不起,我告诉过你它有效,但它并没有完成整个阵列。它似乎只适用于节点本身,以及它的顶部、底部、左侧和右侧的节点。
-
当您递归时,您使用的是后缀运算符
row++等。这些在使用后递增 - 所以您实际上传递的是未更改的row值(更不用说更改以下值来电)。像在 C++ 中一样使用行 + 1.. -
@racraman 这似乎有帮助,但我仍然没有填充所有连接的节点。相反,现在我似乎填充了三个而不是两个。初始“填充点”周围的大多数节点的 int 值不同。
-
同样在您的基本条件下,您应该有 ">= N",或者与 "N -1" 进行比较。将两者都设置为 ">= N -1",您就错过了上限。
标签: java c++ recursion stack-overflow flood-fill