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;
    }
}
相关推荐
炸膛坦客6 小时前
单片机/C/C++八股:(二十)指针常量和常量指针
c语言·开发语言·c++
I_LPL6 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
颜酱6 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
WolfGang0073217 小时前
代码随想录算法训练营 Day16 | 二叉树 part06
算法
炸膛坦客7 小时前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
2401_831824968 小时前
代码性能剖析工具
开发语言·c++·算法
是wzoi的一名用户啊~8 小时前
【C++小游戏】2048
开发语言·c++
Sunshine for you9 小时前
C++中的职责链模式实战
开发语言·c++·算法
qq_416018729 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563249 小时前
模板代码生成工具
开发语言·c++·算法