Skip to content

Commit b079731

Browse files
authored
Create flood-fill.cpp
1 parent e98e015 commit b079731

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

C++/flood-fill.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Time: O(m * n)
2+
// Space: O(m * n)
3+
4+
class Solution {
5+
public:
6+
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
7+
int color = image[sr][sc];
8+
if (color == newColor) return image;
9+
dfs(&image, sr, sc, newColor, color);
10+
return image;
11+
}
12+
13+
private:
14+
void dfs(vector<vector<int>> *image, int r, int c, int newColor, int color) {
15+
static const vector<pair<int, int>> directions{{-1, 0}, { 1, 0},
16+
{ 0, 1}, { 0, -1}};
17+
if (r < 0 || r >= image->size() ||
18+
c < 0 || c >= (*image)[0].size() ||
19+
(*image)[r][c] != color) {
20+
return;
21+
}
22+
(*image)[r][c] = newColor;
23+
for (const auto& d : directions) {
24+
dfs(image, r + d.first, c + d.second, newColor, color);
25+
}
26+
}
27+
};

0 commit comments

Comments
 (0)