【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;
    }
};
相关推荐
Zachery Pole7 小时前
具身智能强化学习(1)引言
算法·机器学习
All for pursuit.7 小时前
【动态规划-11】279.完全平方数
数据结构·c++·算法·leetcode·动态规划
淡海水7 小时前
02-06-原理篇-增量式GC与并发GC
算法·unity·c#·并发·gc·增量
对空六课7 小时前
无头浏览器访问对跳出率的过滤规则
服务器·前端·算法·数据分析
有同事要进步7 小时前
leecode第一题-两数字之和(打卡)
算法
程序员清风7 小时前
二叉搜索树:查找、插入与删除
算法
HRTOS7 小时前
HRTOS 内核 BUG 修复:任务等待对象未初始化导致的异常唤醒问题
单片机·嵌入式硬件·算法·51单片机
XMAIPC_Robot7 小时前
国产FPGA替代Xilinx在储能电力采集场景可行性评估与移植经验
人工智能·算法·机器学习·fpga开发·rk3588+fpga
开开心心就好7 小时前
一元二次方程求解工具,答案带详细步骤
java·服务器·开发语言·算法·pdf·ocr·perl
Logic1018 小时前
C语言/数据结构位运算题解:异或XOR找出套碗游戏中的“幸运碗“——只出现一次的数字
c语言·数据结构·算法·数组·位运算·时间复杂度·空间复杂度