【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;
    }
};
相关推荐
裕晟资质规划1 小时前
武器装备科研生产单位保密资质申请方法论:条件模型与流程拆解
人工智能·算法
en.en..2 小时前
C语言 标准输入 / 输出缓冲区
算法
吃好睡好便好4 小时前
查找函数的使用
学习·算法·matlab·生活·查找函数
学习星球4 小时前
单调栈——从“找下一个更大的“到柱状图中的最大矩形
数据库·c++·算法·leetcode·xcode
靠沿5 小时前
贪心算法专题(二)
算法·贪心算法
猎头南楼6 小时前
具身智能模型部署方向的能力要求与技术栈梳理
人工智能·深度学习·算法
啥都想学点的研究生7 小时前
一篇文章讲清楚:线性回归问题的求解——正规方程法
算法·机器学习·线性回归
青少儿编程课堂7 小时前
树状数组精讲:逆序对计数与离散化(附双语言解法)
算法·树状数组·离散化·信息学奥赛·逆序对
血小板要健康7 小时前
网格 dfs 与 FloodFill:从岛屿、区域到搜索路径
笔记·算法·leetcode·深度优先
VALENIAN瓦伦尼安教学设备8 小时前
设备状态检测振动分析实训台案例分析
大数据·数据库·人工智能·嵌入式硬件·算法