
leetcode-cn.com/problems/fl…
代码如下
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
dfs(image, sr, sc, newColor, image[sr][sc]);
return image;
}
public void dfs(int[][] image, int i, int j, int newColor, int preColor) {
if (i < 0 || i >= image.length || j < 0 || j >= image[0].length || image[i][j] == newColor
|| image[i][j] != preColor) {
return ;
}
int memory = preColor;
image[i][j] = newColor;
dfs(image, i - 1, j, newColor, memory);
dfs(image, i + 1, j, newColor, memory);
dfs(image, i, j - 1, newColor, memory);
dfs(image, i, j + 1, newColor, memory);
}
}