-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathFloodFillDFS.cpp
More file actions
52 lines (43 loc) · 1.25 KB
/
FloodFillDFS.cpp
File metadata and controls
52 lines (43 loc) · 1.25 KB
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
#include <iostream>
#include <vector>
using namespace std;
class FloodFillDFS {
public:
void floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
int oldColor = image[sr][sc];
if (oldColor == newColor) return;
dfs(image, sr, sc, oldColor, newColor);
}
void dfs(vector<vector<int>>& image, int r, int c, int oldColor, int newColor) {
// Boundary check
if (r < 0 || c < 0 || r >= static_cast<int>(image.size()) || c >= static_cast<int>(image[0].size()))
return;
// Stop if color does not match
if (image[r][c] != oldColor)
return;
// Replace color
image[r][c] = newColor;
// Explore neighbors
dfs(image, r + 1, c, oldColor, newColor);
dfs(image, r - 1, c, oldColor, newColor);
dfs(image, r, c + 1, oldColor, newColor);
dfs(image, r, c - 1, oldColor, newColor);
}
};
int main() {
vector<vector<int>> image = {
{1, 1, 1},
{1, 1, 0},
{1, 0, 1}
};
FloodFillDFS solver;
solver.floodFill(image, 1, 1, 2);
// Print output
for (auto& row : image) {
for (int val : row) {
cout << val << " ";
}
cout << endl;
}
return 0;
}