Skip to content

Commit c96d16c

Browse files
committed
Added Flood fill Algorithm
1 parent 5adb139 commit c96d16c

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

Graph/flood_fill.cpp

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
//Problem statement
2+
// An image is represented by a 2-D array of integers,
3+
// each integer representing the pixel value of the image (from 0 to 65535).
4+
// Given a coordinate (sr, sc) representing the starting pixel
5+
// (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image.
6+
// To perform a "flood fill", consider the starting pixel,
7+
// plus any pixels connected 4-directionally to the starting pixel of the same
8+
// color as the starting pixel, plus any pixels connected 4-directionally to those
9+
// pixels (also with the same color as the starting pixel), and so on. Replace the
10+
// color of all of the aforementioned pixels with the newColor.
11+
// At the end, return the modified image.
12+
13+
#include<bits/stdc++.h>
14+
using namespace std;
15+
16+
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
17+
18+
if(image[sr][sc] == newColor)
19+
return image;
20+
21+
queue<int> qx;
22+
queue<int> qy;
23+
24+
int rw = image.size();
25+
int clm = image[0].size();
26+
27+
qx.push(sr);
28+
qy.push(sc);
29+
30+
int curr = image[sr][sc];
31+
image[sr][sc] = newColor;
32+
33+
while( !qx.empty() ) {
34+
35+
int x = qx.front();
36+
int y = qy.front();
37+
38+
qx.pop();
39+
qy.pop();
40+
41+
int arrx[] = {-1, 0, 1, 0};
42+
int arry[] = {0, 1, 0, -1};
43+
44+
for(int i=0; i<4; i++) {
45+
46+
int tempx = x + arrx[i];
47+
int tempy = y + arry[i];
48+
49+
if(tempx <0 || tempy < 0) continue;
50+
if(tempx >=rw || tempy >= clm) continue;
51+
52+
if(image[tempx][tempy] == curr){
53+
qx.push(tempx);
54+
qy.push(tempy);
55+
image[tempx][tempy] = newColor;
56+
}
57+
}
58+
}
59+
60+
return image;
61+
}
62+

0 commit comments

Comments
 (0)