1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { public int[][] floodFill(int[][] image, int sr, int sc, int color) { if (image[sr][sc] == color) return image; helper(image, sr, sc, image[sr][sc], color); image[sr][sc] = color; return image; }
public void helper(int[][] image, int row, int col, int color, int newColor) { if (!isOutOfBound(image, row - 1, col) && image[row - 1][col] == color) { image[row - 1][col] = newColor; helper(image, row - 1, col, color, newColor); } if (!isOutOfBound(image, row + 1, col) && image[row + 1][col] == color) { image[row + 1][col] = newColor; helper(image, row + 1, col, color, newColor); } if (!isOutOfBound(image, row, col - 1) && image[row][col - 1] == color) { image[row][col - 1] = newColor; helper(image, row, col - 1, color, newColor); } if (!isOutOfBound(image, row, col + 1) && image[row][col + 1] == color) { image[row][col + 1] = newColor; helper(image, row, col + 1, color, newColor); } }
public boolean isOutOfBound(int[][] image, int row, int col) { return row < 0 || row >= image.length || col < 0 || col >= image[0].length; } }
|