LeetCode第 733 题:图像渲染(C++)

733. 图像渲染 - 力扣(LeetCode)

类似LeetCode第 130 题:被围绕的区域(C++)_zj-CSDN博客

从初始点开始,相连的才进行染色。

dfs:

class Solution {
public:
    int color, newcolor, m, n;
    void dfs(vector<vector<int>>& image, int sr, int sc){
        if(sr < 0 || sr >= m || sc < 0 || sc >= n || image[sr][sc] !=  color) return;
        image[sr][sc] = newcolor;
        dfs(image, sr-1, sc);
        dfs(image, sr+1, sc);
        dfs(image, sr, sc-1);
        dfs(image, sr, sc+1);
    }
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        if(newColor == image[sr][sc])    return image;//不用染色
        color = image[sr][sc];
        newcolor = newColor;
        m = image.size();//行
        n = image[0].size();//列
        dfs(image, sr, sc);
        return image;
    }
};

bfs

class Solution {
public:
    const int dx[4] = {1,0,0,-1};
    const int dy[4] = {0,1,-1,0};
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        if(newColor == image[sr][sc])    return image;//不用染色
        int color = image[sr][sc];
        int m = image.size(), n = image[0].size();//行、列
        queue<pair<int, int>> q;
        q.push({sr, sc});
        image[sr][sc] = newColor;
        while(!q.empty()){
            int x = q.front().first, y = q.front().second;
            q.pop();
            for(int i = 0; i <4; ++i){//检查上下左右
                int mx = x + dx[i], my = y + dy[i];
                if(mx >= 0 && mx < m && my >= 0 && my < n && image[mx][my] == color){
                    q.push({mx, my});
                    image[mx][my] = newColor;
                }
            }
        }
        return image;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值