【剑斩OFFER】算法的暴力美学——LeetCode 733 题:图像渲染

一、题目描述

二、算法原理

思路:层序遍历(BFS)解决 FloodFill 题

假设从(2,2)开始,我们先把(2,2)入队列,在把 image【 2】【2】 = color ,然后遍历他的上下左右的值是否和他一样 = 1,所以我们把(2,2)入队列之前先保存他对应的值,如果上下左右有值和他一样,那么入队列,直到队列为空;

三、代码实现

cpp 复制代码
class Solution {
    typedef pair<int,int> PII;
    //上下左右的移动值
    int dy[4] = {0,0,-1,1};
    int dx[4] = {-1,1,0,0};
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
        int target = image[sr][sc];//保持原始值
        if(target == color) return image;

        int wight = image[0].size();//宽
        int high = image.size();//高

        queue<PII> que;
        que.push({sr,sc});//使用层序遍历
        image[sr][sc] = color;
        while(que.size())//队列不为空继续查找
        {
            auto [x,y] = que.front();
            que.pop();
            for(int i = 0; i < 4; i++)//上下左右查找符合题目要求的值
            {
                int a = x + dy[i];
                int b = y + dx[i];
                if(a >= 0 && a < high && b >= 0 && b < wight && image[a][b] == target)//符合题目要求
                {
                    image[a][b] = color;
                    que.push({a,b});
                }
            }
        }
        return image;
    }
};
相关推荐
JieE2121 天前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
JieE2122 天前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack202 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树2 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2123 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2123 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术3 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦3 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050733 天前
(一)小红的数组操作
算法·编程语言