Я пытаюсь перевести рекурсивную реализацию с заливкой, которая не использует циклы.Я продолжаю получать ошибку переполнения стека, и я не уверен почему.Я пытался перевести код C ++ здесь .
Как я могу исправить мой 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);
}