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;
    }
}
相关推荐
~山有木兮2 分钟前
C++设计模式 - 单例模式
c++·单例模式·设计模式
十五年专注C++开发15 分钟前
CMake基础:gcc/g++编译选项详解
开发语言·c++·gcc·g++
Q81375746032 分钟前
中阳视角下的资产配置趋势分析与算法支持
算法
yvestine39 分钟前
自然语言处理——文本表示
人工智能·python·算法·自然语言处理·文本表示
HUN金克斯1 小时前
C++/C函数
c语言·开发语言·c++
慢半拍iii1 小时前
数据结构——F/图
c语言·开发语言·数据结构·c++
GalaxyPokemon1 小时前
LeetCode - 148. 排序链表
linux·算法·leetcode
iceslime1 小时前
旅行商问题(TSP)的 C++ 动态规划解法教学攻略
数据结构·c++·算法·算法设计与分析
虾球xz2 小时前
CppCon 2015 学习:3D Face Tracking and Reconstruction using Modern C++
开发语言·c++·学习·3d
aichitang20242 小时前
矩阵详解:从基础概念到实际应用
线性代数·算法·矩阵