Leetcode 733. Flood Fill

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Flood Fill

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
int rows = image.size();
int columns = image[0].size();
vector<vector<int>> flag(rows, vector<int>(columns));
int oldColor = image[sr][sc];
floodFill(image, sr, sc, newColor, oldColor, rows, columns, flag);
return image;
}

private:
void floodFill(vector<vector<int>>& image, int sr, int sc, int& newColor, int& oldColor, int& rows, int& columns, vector<vector<int>>& flag) {
if(sr < 0 || sr == rows || sc < 0 || sc == columns || image[sr][sc] != oldColor || flag[sr][sc]) {
return;
}
image[sr][sc] = newColor;
flag[sr][sc] = 1;
floodFill(image, sr + 1, sc, newColor, oldColor, rows, columns, flag);
floodFill(image, sr - 1, sc, newColor, oldColor, rows, columns, flag);
floodFill(image, sr, sc + 1, newColor, oldColor, rows, columns, flag);
floodFill(image, sr, sc - 1, newColor, oldColor, rows, columns, flag);
}
};
  • Version 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
int rows = image.size();
int columns = image[0].size();
int oldColor = image[sr][sc];
floodFill(image, sr, sc, newColor, oldColor, rows, columns);
return image;
}

private:
void floodFill(vector<vector<int>>& image, int sr, int sc, int& newColor, int& oldColor, int& rows, int& columns) {
if(sr < 0 || sr == rows || sc < 0 || sc == columns || image[sr][sc] != oldColor || image[sr][sc] == newColor) {
return;
}
image[sr][sc] = newColor;
floodFill(image, sr + 1, sc, newColor, oldColor, rows, columns);
floodFill(image, sr - 1, sc, newColor, oldColor, rows, columns);
floodFill(image, sr, sc + 1, newColor, oldColor, rows, columns);
floodFill(image, sr, sc - 1, newColor, oldColor, rows, columns);
}
};

Reference

  1. https://leetcode.com/problems/flood-fill/description/
如果有收获,可以请我喝杯咖啡!