-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlood Fill Algo
36 lines (30 loc) · 1.05 KB
/
Flood Fill Algo
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
class Solution {
public:
void dfs(vector<vector<int>>& image, int sr, int sc, int color, int oldcolor, vector<vector<int>>& visited) {
vector<int> xRay = {0, 0, -1, 1};
vector<int> yRay = {-1, 1, 0, 0};
image[sr][sc] = color;
for (int i = 0; i < 4; i++) {
int newRow = sr + xRay[i];
int newCol = sc + yRay[i];
if (newRow >= 0 && newRow < image.size() &&
newCol >= 0 && newCol < image[0].size() &&
visited[newRow][newCol] == 0 &&
image[newRow][newCol] == oldcolor) {
visited[newRow][newCol] = 1;
image[newRow][newCol] = color;
dfs(image, newRow, newCol, color, oldcolor, visited);
}
}
}
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
int n = image.size();
int k = image[0].size();
int oldcolor = image[sr][sc];
vector<vector<int>> visited(n, vector<int>(k, 0));
visited[sr][sc] = 1;
image[sr][sc] = color;
dfs(image, sr, sc, color, oldcolor, visited);
return image;
}
};