洪水问题,需要注意当target和目标值一样时,应该怎么处理。
class Solution {
public:
void func(vector<vector<int>>& image, int sr, int sc, int newColor, int oldColor) {
int row = image.size();
int col = image[0].size();
image[sr][sc] = newColor;
// [sr-1, sc] [sr+1, sc] [sr, sc-1] [sr, sc+1]
if (sr-1>=0&&sr-1<row&&sc>=0&&sc<col&&image[sr-1][sc]==oldColor){
image[sr-1][sc] = newColor;
func(image, sr-1, sc, newColor,oldColor);
}
if (sr+1>=0&&sr+1<row&&sc>=0&&sc<col&&image[sr+1][sc]==oldColor){
image[sr+1][sc] = newColor;
func(image, sr+1, sc, newColor,oldColor);
}
if (sr>=0&&sr<row&&sc-1>=0&&sc-1<col&&image[sr][sc-1]==oldColor){
image[sr][sc-1] = newColor;
func(image, sr, sc-1, newColor,oldColor);
}
if (sr>=0&&sr<row&&sc+1>=0&&sc+1<col&&image[sr][sc+1]==oldColor){
image[sr][sc+1] = newColor;
func(image, sr, sc+1, newColor,oldColor);
}
}
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
if (image[sr][sc]==newColor){
return image;
}
else{
func(image, sr, sc, newColor, image[sr][sc]);
return image;
}
}
};