# Leetcode 733. Flood Fill

## 2. Solution

• Version 1
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
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);
}
};


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120