BFS 专题 ——FloodFill算法:733.图像渲染

文章目录

前言

大家好啊,今天就正式开始我们的BFS专题了,觉得有用的朋友给个三连呗。

FloodFill算法简介

中文:洪水灌溉

举个例子,正数为凸起的山峰,负数为盆地,洪水冲过这片土地就会将这些具有相同性质的联通块 (在本例中为盆地)灌溉。

题目描述

题目链接:733.图像渲染

简单来说就是给我们一个起点坐标,让我们从上下左右四个方向去找相同像素点的坐标。

算法原理

可以利用深搜或者宽搜,遍历到与该点相连的所有像素相同的点,然后将其修改成指定的像素值即可。

本篇博客使用的是BFS,每条斜线代表每一层遍历。

代码实现------BFS

C++

cpp 复制代码
class Solution {
    typedef pair<int, int> PII;//技巧一
    int dx[4] = {0, 0, 1, -1};//技巧二:对应上下左右四个方向的坐标
    int dy[4] = {1, -1, 0, 0};

public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc,int color) {
        int prev = image[sr][sc];
        if (prev == color)
            return image; // 处理边界情况
        int m = image.size(), n = image[0].size();
        queue<PII> q;
        q.push({sr, sc});
        while (!q.empty()) {
            auto [a, b] = q.front();
            image[a][b] = color;
            q.pop();
            for (int i = 0; i < 4; ++i) {
                int x = a + dx[i], y = b + dy[i];
                if (x >= 0 && x < m && y >= 0 && y < n && image[x][y] == prev) {
                    q.push({x, y});
                }
            }
        }
        return image;
    }
};

Java

java 复制代码
class Solution {
    int[] dx = { 0, 0, 1, -1 };
    int[] dy = { 1, -1, 0, 0 };

    public int[][] floodFill(int[][] image, int sr, int sc, int color) {
        int prev = image[sr][sc]; // 统计刚开始的颜⾊
        if (prev == color)
            return image; // 处理边界情况
        int m = image.length, n = image[0].length;
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[] { sr, sc });
        while (!q.isEmpty()) {
            int[] t = q.poll();
            int a = t[0], b = t[1];
            image[a][b] = color;
            // 上下左右四个⽅向
            for (int i = 0; i < 4; i++) {
                int x = a + dx[i], y = b + dy[i];
                if (x >= 0 && x < m && y >= 0 && y < n && image[x][y] == prev) {
                    q.add(new int[] { x, y });
                }
            }
        }
        return image;
    }
}
相关推荐
阿客不是客7 分钟前
深入计算机语言之C++:C到C++的过度
c++
LN-ZMOI14 分钟前
c++学习笔记1
c++·笔记·学习
数据分析螺丝钉17 分钟前
力扣第240题“搜索二维矩阵 II”
经验分享·python·算法·leetcode·面试
no_play_no_games17 分钟前
「3.3」虫洞 Wormholes
数据结构·c++·算法·图论
￴ㅤ￴￴ㅤ9527超级帅18 分钟前
LeetCode hot100---数组及矩阵专题(C++语言)
c++·leetcode·矩阵
五味香18 分钟前
C++学习,信号处理
android·c语言·开发语言·c++·学习·算法·信号处理
毕小宝42 分钟前
逻辑回归(下): Sigmoid 函数的发展历史
算法·机器学习·逻辑回归
小叮当爱咖啡1 小时前
DenseNet算法:口腔癌识别
算法
希望有朝一日能如愿以偿1 小时前
算法(食物链)
算法
鱼跃鹰飞1 小时前
Leecode热题100-295.数据流中的中位数
java·服务器·开发语言·前端·算法·leetcode·面试