-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0733-flood-fill.java
More file actions
27 lines (26 loc) · 996 Bytes
/
0733-flood-fill.java
File metadata and controls
27 lines (26 loc) · 996 Bytes
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
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int color = image[sr][sc];
if (color != newColor)
BFS(image, sr, sc, color, newColor);
return image;
}
public void BFS(int[][] image, int i, int j, int color, int newColor) {
Queue<int[]> q = new LinkedList<>();
q.offer(new int []{i, j});
while (!q.isEmpty()) {
int size = q.size();
for (int k=0; k<size; k++) {
int[] curr = q.poll();
int x = curr[0], y = curr[1];
if (image[x][y] == color) {
image[x][y] = newColor;
if (x > 0) q.offer(new int[] {x-1, y});
if (x < image.length-1) q.offer(new int[] {x+1, y});
if (y > 0) q.offer(new int[] {x, y-1});
if (y < image[0].length-1) q.offer(new int[] {x, y+1});
}
}
}
}
}