【问题标题】:Translating C++ recursive floodfill implementation for 2D array without any loops, into Java?将没有任何循环的 2D 数组的 C++ 递归填充实现转换为 Java?
【发布时间】: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


【解决方案1】:

我需要将pic[row][col] = newC 行放入程序中。另一个问题是我不知道variableName++ 是与variableName + 1 不同的命令,因此递归没有按预期工作。 variableName++ 返回variableName 的值之前它被增加了。

这段代码让我的程序可以运行:

public void floodFill(int[][] pic, int row, int col, int oldC, int newC) {

  // Base Cases
  if(row < 0 || col < 0 || row >= pic.length || col >= pic[row].length) {
     return;
  }
  if(pic[row][col] != oldC) {
     return;
  }

  pic[row][col] = newC;

  // recursion
  floodFill(pic, row + 1, col, oldC, newC);
  floodFill(pic, row - 1, col, oldC, newC);
  floodFill(pic, row, col + 1, oldC, newC);
  floodFill(pic, row, col - 1, oldC, newC);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2017-03-30
    • 2013-07-20
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    相关资源
    最近更新 更多