【LeetCode热题100】【图论】腐烂的橘子

题目描述:994. 腐烂的橘子 - 力扣(LeetCode)

腐烂的橘子会污染周围的橘子,要求多少轮扩散才能把全部橘子污染,这就相当于滴墨水入清水,会扩散,其实就是广度遍历,看看遍历多少层可以遍历完可以遍历的

先遍历一次橘子,记录下腐烂橘子的位置和新鲜橘子的数目,然后广度遍历腐烂橘子并向外扩散污染新鲜橘子

注意向外扩散时需要每次取位置,因为移动会改变位置,位置需要重置

复制代码
class Solution {
public:
    int rows, columns;
    vector<vector<int> > grid;

    bool isValid(int x, int y) {
        return x >= 0 && y >= 0 && x < rows && y < columns;
    }

    int orangesRotting(vector<vector<int> > &grid) {
        rows = grid.size();
        columns = grid[0].size();
        this->grid = move(grid);
        int ans = 0, fresh = 0;
        queue<pair<int, int> > pullte;
        for (int i = 0; i < rows; ++i)
            for (int j = 0; j < columns; ++j)
                if (this->grid[i][j] == 1)
                    ++fresh;
                else if (this->grid[i][j] == 2)
                    pullte.emplace(i, j);
        int move[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        while (fresh > 0 && !pullte.empty()) {
            int scale = pullte.size();
            while (--scale >= 0) {
                for (int i = 0; i < 4; ++i) {
                    auto [x,y] = pullte.front();
                    x += move[i][0];
                    y += move[i][1];
                    if (isValid(x, y) && this->grid[x][y] == 1) {
                        this->grid[x][y] = 2;
                        pullte.emplace(x, y);
                        --fresh;
                    }
                }
                pullte.pop();
            }
            ++ans;
        }
        if (fresh > 0)
            return -1;
        return ans;
    }
};
相关推荐
探物 AI7 分钟前
【感知·医学分割】当 YOLOv11 杀入医学赛道:先检测后分割的级联架构
算法·yolo·计算机视觉·架构
隔壁大炮14 分钟前
Day06-08.CNN概述介绍
人工智能·pytorch·深度学习·算法·计算机视觉·cnn·numpy
白云千载尽14 分钟前
前馈与反馈——经典控制理论中的基础概念
人工智能·算法
炽烈小老头26 分钟前
【每日天学习一点算法 2026/04/27】缺失的第一个正数
学习·算法
南宫萧幕1 小时前
HEV 智能能量管理实战:从 MPC/PPO 理论解析到 Python-Simulink 联合仿真闭环全流程
开发语言·python·算法·matlab·控制
啦啦啦_99991 小时前
1. 一元/多元线性回归之 正规方程求解法
算法·回归·线性回归
ECT-OS-JiuHuaShan1 小时前
整体论体系定理,全球开放,无法绕过
人工智能·科技·学习·算法·生活
贾斯汀玛尔斯1 小时前
每天学一个算法--BM25(Okapi BM25)
算法
grant-ADAS2 小时前
Overlay套刻测量
算法
猿长大人2 小时前
算法 | Douglas-Peucker 拯救“腰椎间盘突出的三角形”
算法