1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int color = image[sr][sc]; if (color != newColor) { dfs(image, sr, sc, color, newColor); } return image; }
private void dfs(int[][] image, int sr, int sc, int color, int newColor) { if (sr < 0 || sc < 0 || sr >= image.length || sc >= image[0].length) { return; } if (image[sr][sc] != color || image[sr][sc] == newColor) { return; } image[sr][sc] = newColor; dfs(image, sr - 1, sc, color, newColor); dfs(image, sr + 1, sc, color, newColor); dfs(image, sr, sc - 1, color, newColor); dfs(image, sr, sc + 1, color, newColor); } }
|