Paint Fill:很多图片处理软件都包含填充的功能,使用一个颜色将一片区域填充为用户当前选中的颜色。
和当前像素相邻的有4
个像素,如果这些像素的原始颜色和当前像素的原始颜色相同,就填充相邻的四个像素。
特别要注意新的颜色和旧颜色相同的情况,这种情况不需要进行填充,如果进行填充则会溢出。
写四次类似的递归特别容易出错,或许有更好的办法。
class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
height = image.size();
width = image[0].size();
color = image[sr][sc];
if(color != newColor) fillColor(image, sr, sc, newColor);
return image;
}
private:
int color, width, height;
void fillColor(vector<vector<int>> &image, int sr, int sc, int newColor)
{
image[sr][sc] = newColor;
if(sr - 1 >= 0 && image[sr - 1][sc] == color){
fillColor(image, sr - 1, sc, newColor);
}
if(sc - 1 >= 0 && image[sr][sc - 1] == color){
fillColor(image, sr, sc - 1, newColor);
}
if(sr + 1 < height && image[sr + 1][sc] == color){
fillColor(image, sr + 1, sc, newColor);
}
if(sc + 1 < width && image[sr][sc + 1] == color){
fillColor(image, sr, sc + 1, newColor);
}
}
};