-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_733_FloodFill.cpp
76 lines (56 loc) · 2.3 KB
/
LC_733_FloodFill.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
https://leetcode.com/problems/flood-fill/
733. Flood Fill
*/
//LeetCode
class Solution {
public:
int newTarget, oldTarget;
int m,n;
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
m = image.size();
n = image[0].size();
newTarget = newColor;
oldTarget = image[sr][sc];
bfsFloodFill(image, sr, sc);
// dfsFloodFill(image, sr, sc, newColor, image[sr][sc], image.size(), image[0].size());
return image;
}// end
void bfsFloodFill(vector<vector<int>>& matrix, int r, int c)
{
queue<pair<int,int>> q;
// int r, c;
q.push({r,c});
while(!q.empty())
{
auto [r,c] = q.front();
q.pop();
if(matrix[r][c] == newTarget)
continue;
matrix[r][c]=newTarget;
if(r-1>=0 && matrix[r-1][c] == oldTarget)
q.push({r-1, c}); // top
if(r+1<m && matrix[r+1][c] == oldTarget)
q.push({r+1, c}); // bottom
if(c-1>=0 && matrix[r][c-1] == oldTarget)
q.push({r, c-1}); // left
if(c+1<n && matrix[r][c+1] == oldTarget)
q.push({r, c+1}); // right
}
}//
//oldColor is what needed to change orginally.
//newColor is what is needed to update
void dfsFloodFill(vector<vector<int>>& image, int sr, int sc, int newColor, int oldColor, int m, int n){
if(image[sr][sc] == newColor) return; // if it is already updated then no need to change
image[sr][sc] = newColor; // update with new color.
// it should be within bound and pixel value should be oldColor.
if(sc-1 >=0 && image[sr][sc-1] == oldColor)
dfsFloodFill(image, sr, sc-1, newColor, oldColor, m, n); //left
if(sr-1 >=0 && image[sr-1][sc] == oldColor)
dfsFloodFill(image, sr-1, sc, newColor, oldColor, m, n); //top
if(sc+1 <n && image[sr][sc+1] == oldColor)
dfsFloodFill(image, sr, sc+1, newColor, oldColor, m, n); //right
if(sr+1 <m && image[sr+1][sc] == oldColor)
dfsFloodFill(image, sr+1, sc, newColor, oldColor, m, n); // bottom
}//dfsFloodFill
};