|
| 1 | +class Solution { |
| 2 | + /*public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { |
| 3 | + if (image[sr][sc] == newColor) return image; |
| 4 | + dfs(image, sr, sc, image[sr][sc], newColor); |
| 5 | + return image; |
| 6 | + } |
| 7 | +
|
| 8 | + private void dfs(int[][] image, int r, int c, int color, int newColor) { |
| 9 | + // Recursively DFS |
| 10 | + if (image[r][c] == color) { |
| 11 | + image[r][c] = newColor; |
| 12 | + if (r - 1 >= 0) dfs(image, r - 1, c, color, newColor); |
| 13 | + if (r + 1 < image.length) dfs(image, r + 1, c, color, newColor); |
| 14 | + if (c - 1 >= 0) dfs(image, r, c - 1, color, newColor); |
| 15 | + if (c + 1 < image[0].length) dfs(image, r, c + 1, color, newColor); |
| 16 | + } |
| 17 | + }*/ |
| 18 | + |
| 19 | + public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { |
| 20 | + Queue<Node> queue = new LinkedList<Node>(); |
| 21 | + int color = image[sr][sc]; |
| 22 | + if (color == newColor) return image; |
| 23 | + queue.add(new Node(sr, sc)); |
| 24 | + // BFS with queue |
| 25 | + while (!queue.isEmpty()) { |
| 26 | + Node curr = queue.remove(); |
| 27 | + int r = curr.r, c = curr.c; |
| 28 | + if (image[r][c] == color) { |
| 29 | + image[r][c] = newColor; |
| 30 | + if (r - 1 >= 0) queue.add(new Node(r - 1, c)); |
| 31 | + if (r + 1 < image.length) queue.add(new Node(r + 1, c)); |
| 32 | + if (c - 1 >= 0) queue.add(new Node(r, c - 1)); |
| 33 | + if (c + 1 < image[0].length) queue.add(new Node(r, c + 1)); |
| 34 | + } |
| 35 | + } |
| 36 | + return image; |
| 37 | + } |
| 38 | + |
| 39 | + class Node { |
| 40 | + int r; |
| 41 | + int c; |
| 42 | + |
| 43 | + public Node(int r, int c) { |
| 44 | + this.r = r; |
| 45 | + this.c = c; |
| 46 | + } |
| 47 | + } |
| 48 | +} |
0 commit comments