| 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; |