-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlood-Fill.cpp
45 lines (42 loc) · 1.08 KB
/
Flood-Fill.cpp
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<vector<int>> floodFill(vector<vector<int>> &image, int sr, int sc, int color)
{
if (image[sr][sc] == color)
return image;
int prevColor = image[sr][sc], n = image.size(), m = image[0].size();
queue<pair<int, int>> q;
q.push({sr, sc});
while (!q.empty())
{
int nr = q.front().first, nc = q.front().second;
q.pop();
image[nr][nc] = color;
if (nr - 1 >= 0 && image[nr - 1][nc] == prevColor)
q.push({nr - 1, nc});
if (nr + 1 < n && image[nr + 1][nc] == prevColor)
q.push({nr + 1, nc});
if (nc - 1 >= 0 && image[nr][nc - 1] == prevColor)
q.push({nr, nc - 1});
if (nc + 1 < m && image[nr][nc + 1] == prevColor)
q.push({nr, nc + 1});
}
return image;
}
};
int main()
{
Solution st;
vector<vector<int>> image = {{0, 0, 0}, {0, 0, 0}};
vector<vector<int>> ans = st.floodFill(image, 1, 0, 2);
for (auto chVect : ans)
{
for (auto el : chVect)
cout << el << " ";
cout << endl;
}
return 0;
}