【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;
    }
};
相关推荐
美式请加冰2 分钟前
子序列问题
数据结构·算法·leetcode
DeniuHe4 分钟前
线性回归与逻辑回归:同为凸函数,为何一个有解析解、一个没有?
算法·机器学习·逻辑回归
披着羊皮不是狼8 分钟前
基于CNN的图像检测算法
人工智能·算法·cnn
程序员小崔日记8 分钟前
我参加了第十七届蓝桥杯 Java B 组省赛,这套题你能撑到第几题?
java·算法·蓝桥杯大赛
6Hzlia29 分钟前
【Hot 100 刷题计划】 LeetCode 1143. 最长公共子序列 | C++ 二维DP 与 哨兵技巧
c++·算法·leetcode
Allen_LVyingbo38 分钟前
《狄拉克符号法50讲》习题与解析(下)
算法·决策树·机器学习·健康医疗·量子计算
豆沙糕38 分钟前
大模型面试高频题:请详细讲解检索中的BM25算法
人工智能·算法
不才小强39 分钟前
查找算法详解:二分查找
数据结构·算法
君义_noip42 分钟前
信息学奥赛一本通 4164:【GESP2512七级】学习小组 | 洛谷 P14922 [GESP202512 七级] 学习小组
学习·算法·动态规划·gesp·信息学奥赛
MicroTech202542 分钟前
微算法科技(NASDAQ :MLGO)面向区块链的系统的高效反量子晶格盲签名技术
科技·算法·区块链