-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlood Fill - Easy
35 lines (29 loc) · 1.09 KB
/
Flood Fill - Easy
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
class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
int n = image.size();
int m = image[0].size();
int color = image[sr][sc];
image[sr][sc] = newColor;
DFS(image, sr + 1, sc, n, m, color, newColor);
DFS(image, sr - 1, sc, n, m, color, newColor);
DFS(image, sr, sc + 1, n, m, color, newColor);
DFS(image, sr, sc - 1, n, m, color, newColor);
return image;
}
void DFS(vector<vector<int>>& image, int i, int j, int n, int m, int color, int newColor)
{
if (i < 0 || j < 0 || i > (n - 1) || j > (m - 1) || image[i][j] != color || image[i][j]==newColor)
{
return;
}
if (image[i][j] == color)
{
image[i][j] = newColor;
DFS(image, i + 1, j, n, m, color, newColor);
DFS(image, i - 1, j, n, m, color, newColor);
DFS(image, i, j + 1, n, m, color, newColor);
DFS(image, i, j - 1, n, m, color, newColor);
}
}
};