Skip to content

Commit bbe6889

Browse files
Implement Flood Fill algorithm in FloodFill.java
1 parent ec9a1f0 commit bbe6889

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Graphs/Problems/FloodFill.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class FloodFill {
2+
public int[][] floodFill(int[][] image, int sr, int sc, int color) {
3+
int n = image.length;
4+
int m = image[0].length;
5+
int startingColor = image[sr][sc];
6+
7+
if(startingColor == color){
8+
return image;
9+
}
10+
11+
Queue<int[]> q = new LinkedList<>();
12+
13+
q.add(new int[]{sr,sc});
14+
15+
while(!q.isEmpty()){
16+
int[] coord = q.remove();
17+
int row = coord[0];
18+
int col = coord[1];
19+
image[row][col] = color;
20+
if(row-1>= 0 && image[row-1][col] == startingColor){
21+
q.add(new int[]{row-1,col});
22+
image[row-1][col] = color;
23+
}
24+
if(row+1<n && image[row+1][col] == startingColor){
25+
q.add(new int[]{row+1,col});
26+
image[row+1][col] = color;
27+
}
28+
if(col-1>=0 && image[row][col-1] == startingColor){
29+
q.add(new int[]{row,col-1});
30+
image[row][col-1] = color;
31+
}
32+
if(col+1<m && image[row][col+1] == startingColor){
33+
q.add(new int[]{row,col+1});
34+
image[row][col+1] = color;
35+
}
36+
}
37+
38+
return image;
39+
}
40+
}

0 commit comments

Comments
 (0)