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;
    }
}
相关推荐
Ulyanov2 分钟前
顶层设计——单脉冲雷达仿真器的灵魂蓝图
python·算法·pyside·仿真系统·单脉冲
智者知已应修善业1 小时前
【查找字符最大下标以*符号分割以**结束】2024-12-24
c语言·c++·经验分享·笔记·算法
91刘仁德2 小时前
c++类和对象(下)
c语言·jvm·c++·经验分享·笔记·算法
diediedei2 小时前
模板编译期类型检查
开发语言·c++·算法
阿杰学AI2 小时前
AI核心知识78——大语言模型之CLM(简洁且通俗易懂版)
人工智能·算法·ai·语言模型·rag·clm·语境化语言模型
mmz12072 小时前
分治算法(c++)
c++·算法
一切尽在,你来2 小时前
C++多线程教程-1.2.1 C++11/14/17 并发特性迭代
开发语言·c++
睡一觉就好了。3 小时前
快速排序——霍尔排序,前后指针排序,非递归排序
数据结构·算法·排序算法
80530单词突击赢3 小时前
C++入门指南:从零到精通
开发语言·c++
Tansmjs3 小时前
C++编译期数据结构
开发语言·c++·算法