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;
    }
}
相关推荐
Maỿbe6 分钟前
力扣hot图论部分
算法·leetcode·图论
雍凉明月夜9 分钟前
c++ 精学笔记记录Ⅲ
c++·笔记·学习
LYFlied14 分钟前
【每日算法】LeetCode 78. 子集
数据结构·算法·leetcode·面试·职场和发展
月明长歌18 分钟前
【码道初阶】【Leetcode606】二叉树转字符串:前序遍历 + 括号精简规则,一次递归搞定
java·数据结构·算法·leetcode·二叉树
子枫秋月19 分钟前
C++字符串操作与迭代器解析
数据结构·算法
鹿角片ljp19 分钟前
力扣234.回文链表-反转后半链表
算法·leetcode·链表
(●—●)橘子……20 分钟前
记力扣1471.数组中的k个最强值 练习理解
数据结构·python·学习·算法·leetcode
oioihoii23 分钟前
C++共享内存小白入门指南
java·c++·算法
布茹 ei ai25 分钟前
QtWeatherApp - 简单天气预报软件(C++ Qt6)(附源码)
开发语言·c++·qt·开源·开源项目·天气预报
Bruce_kaizy25 分钟前
c++图论————图的基本与遍历
c++·算法·图论