733. Flood Fill

An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).

Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, “flood fill” the image.

To perform a “flood fill”, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.

At the end, return the modified image.

这题很简单,常见的深度优先搜索很适合。但我一开始提交的时候有些测试用例并不对,原因是newcolor 和原始像素值一致。深度优先一个很重要的问题就是访问过的数据需要被有效标记,避免二次访问,当newcolor跟原始数据一致的时候,改变原始数据并不能产生想要的标记效果,导致无法跳出递归的循环。

代码:

class Solution {
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        vector<vector<int>> res(image);
        helper(res, sr, sc, newColor);
        return res;
    }
    void helper(vector<vector<int>>& res, int sr, int sc, int newColor) {
        int oriColor = res[sr][sc];
        res[sr][sc] = newColor;
        int nrow = res.size();
        if (nrow < 1) return;
        int ncol = res[0].size();
        if (sr - 1 >= 0 && res[sr - 1][sc] == oriColor && res[sr - 1][sc] != newColor) {
            helper(res, sr - 1, sc, newColor);
        }
        if (sr + 1 < nrow && res[sr + 1][sc] == oriColor && res[sr + 1][sc] != newColor) {
            helper(res, sr + 1, sc, newColor);
        }
        if (sc - 1 >= 0 && res[sr][sc - 1] == oriColor && res[sr][sc - 1] != newColor) {
            helper(res, sr, sc - 1, newColor);
        }
        if (sc + 1 < ncol && res[sr][sc + 1] == oriColor && res[sr][sc + 1] != newColor) {
            helper(res, sr, sc + 1, newColor);
        }
        return;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值