Skip to content

Commit c31d5fb

Browse files
authored
Create 12 April Flood fill Algorithm (#765)
2 parents 2fe55ac + fa7d6f0 commit c31d5fb

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

12 April Flood fill Algorithm

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
vector<vector<int>> floodFill(vector<vector<int>>& image,
2+
int sr, int sc, int newColor) {
3+
// Code here
4+
int n=image.size();
5+
int m=image[0].size();
6+
7+
int dr[4]={-1, 0, 1, 0};
8+
int dc[4]={0, 1, 0, -1};
9+
10+
int orgColor=image[sr][sc];
11+
if (orgColor == newColor) return image;
12+
image[sr][sc]=newColor;
13+
14+
queue<pair<int, int>>q;
15+
16+
q.push({sr, sc});
17+
18+
while(!q.empty()){
19+
auto &it=q.front();
20+
int r=it.first;
21+
int c=it.second;
22+
q.pop();
23+
24+
for(int i=0; i<4; i++){
25+
int nr=r+dr[i];
26+
int nc=c+dc[i];
27+
if(nr>=0 && nr<n && nc>=0 && nc<m &&
28+
image[nr][nc]==orgColor){
29+
q.push({nr, nc});
30+
image[nr][nc]=newColor;
31+
}
32+
}
33+
}
34+
return image;
35+
}

0 commit comments

Comments
 (0)