Перевести C ++ рекурсивную реализацию разлива для 2D-массива без каких-либо циклов в Java? - PullRequest
0 голосов
/ 13 декабря 2018

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

1 Ответ

0 голосов
/ 16 декабря 2018

Мне нужно было поставить строку 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);
}
...