Skip to content

Commit a934666

Browse files
committed
general bfs to fill the matrix
1 parent d396841 commit a934666

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

BFS/floodFill.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Point {
2+
int x;
3+
int y;
4+
public Point(int x, int y) {
5+
this.x = x;
6+
this.y = y;
7+
}
8+
}
9+
class Solution {
10+
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
11+
int[][] dir = {{0,-1}, {-1,0}, {0,1}, {1,0}};
12+
Queue<Point> q = new LinkedList<>();
13+
Point newPoint = new Point(sr, sc);
14+
int prevColor = image[sr][sc];
15+
if (prevColor != newColor) {
16+
q.add(newPoint);
17+
}
18+
while(!q.isEmpty()) {
19+
int s = q.size();
20+
for (int i=0; i<s; i++) {
21+
Point poll = q.poll();
22+
image[poll.x][poll.y] = newColor;
23+
for (int[] d: dir) {
24+
Point new_point = new Point(d[0] + poll.x, d[1] + poll.y);
25+
if (new_point.x >= 0 && new_point.x < image.length && new_point.y >= 0 && new_point.y < image[0].length && image[new_point.x][new_point.y] == prevColor) {
26+
image[new_point.x][new_point.y] = 2;
27+
q.add(new_point);
28+
}
29+
}
30+
}
31+
}
32+
33+
return image;
34+
}
35+
}

0 commit comments

Comments
 (0)