LeetCode 733. Flood Fill

189 阅读2分钟

LeetCode 733. Flood Fill

有一幅以 m x n 的二维整数数组表示的图画 image ,其中 image[i][j] 表示该图画的像素值大小。

你也被给予三个整数 sr ,  sc 和 newColor 。你应该从像素 image[sr][sc] 开始对图像进行 上色填充 。

为了完成 上色工作 ,从初始像素开始,记录初始坐标的 上下左右四个方向上 像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应 四个方向上 像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为 newColor 。

最后返回 经过上色渲染后的图像

示例 1:

输入: image = [[1,1,1],[1,1,0],[1,0,1]],sr = 1, sc = 1, newColor = 2
输出: [[2,2,2],[2,2,0],[2,0,1]]
解析: 在图像的正中间,(坐标(sr,sc)=(1,1)),在路径上所有符合条件的像素点的颜色都被更改成2。
注意,右下角的像素没有更改为2,因为它不是在上下左右四个方向上与初始点相连的像素点。

示例 2:

输入: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2
输出: [[2,2,2],[2,2,2]]

提示:

  • m == image.length
  • n == image[i].length
  • 1 <= m, n <= 50
  • 0 <= image[i][j], newColor < 216
  • 0 <= sr < m
  • 0 <= sc < n

算法1

(DFS) O(N)
洪水填充/简单染色问题。
当前点(x,y)的四周可以借助两个数组来表示,dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1},那么四周的坐标分别是x=sr+dx[i],y=sc+dy[i],i=0,1,2,3
依次检查当前点的四个邻接点是否满足条件(颜色一样),是的话递归调用floddFill()
注:以下DFS code by yxc.

C++ 代码

class Solution {
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        if (image[sr][sc] == newColor) return image;
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        int rawColor = image[sr][sc];
        image[sr][sc] = newColor;
        for (int i = 0; i < 4; i ++ )
        {
            int x = sr + dx[i], y = sc + dy[i];
            if (x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && image[x][y] == rawColor)
                floodFill(image, x, y, newColor);
        }
        return image;
    }
};

算法2

(BFS) O(N)
从当前像素点(sr, sc)开始,修改颜色,并遍历四周,相同颜色则加入queue
没有得加的时候,从queue中取出像素点,设置为当前像素点
重复1、2,直到queue为空
注意,要用一个额外的二维数组表示某个点是否进入过queue,避免重复进入。

C++ 代码

vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
    if (image[sr][sc] == newColor) return image;
    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    int rawColor = image[sr][sc]; //保存下来初始像素点的颜色,后面用于判断

    vector<vector<int>> visit(image.size(),vector<int>(image[0].size(),0)); //visit数组用来保存当前点是否访问过
    queue<int> tofillx, tofilly;
    tofillx.push(sr);
    tofilly.push(sc);
    visit[sr][sc]=1; //标记已访问过该点

    while(!tofillx.empty()){
        sr = tofillx.front();
        sc = tofilly.front(); //(sr,sc)为当前中心像素点
        tofillx.pop(); //注意pop是没有返回值的
        tofilly.pop();
        image[sr][sc] = newColor; //给当前点染色

        for(int i=0; i<4; ++i){ //遍历
            int x = sr + dx[i], y = sc + dy[i];
            if (x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && visit[x][y]==0 && image[x][y] == rawColor){
                tofillx.push(x);
                tofilly.push(y);
                visit[x][y]=1; //标记已访问过该点
            }
        }
    }

    return image;
}