简单多源BFS问题

力扣问题:994. 腐烂的橘子

注意点:多源BFS写法(本质层序遍历)、move数组的使用

cpp 复制代码
class Solution {
public:
    int orangesRotting(vector<vector<int>>& grid) {
        int n = grid.size();
        int m = grid[0].size();
        int fresh = 0;        // 记录未被遍历到的位置个数
        queue<pair<int, int>> q;
        vector<int> move = {-1, 0, 1, 0, -1};
        int ans = 0;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                int type = grid[i][j];
                if (type == 0)
                    continue;
                if (type == 1)
                    fresh++;
                if (type == 2)
                    q.push({i, j});
            }
        }

        while (!q.empty() && fresh) {
            ans++;        // 步数加一
            int count = q.size();
            // 注意循环时机
            for (int i = 1; i <= count; i++) {
                auto current = q.front();
                q.pop();
                for (int j = 0; j < 4; j++) {
                    int x = current.first + move[j];
                    int y = current.second + move[j + 1];
                    if (x >= 0 && x < n && y >= 0 && y < m && grid[x][y] == 1) {
                        grid[x][y] = 2;
                        fresh--;
                        q.push({x, y});
                    }
                }
            }
        }

        return fresh != 0 ? -1 : ans;
    }
};
相关推荐
开开心心就好3 分钟前
自动生成小学数学题库支持导出Word
人工智能·安全·leetcode·贪心算法·ocr·音视频·语音识别
bIo7lyA8v4 分钟前
算法复杂度的可视化评估与优化策略研究的技术8
算法
Skrrapper12 分钟前
从 DeepSeek、Qwen 到 GPT:一次企业级 AI 知识库项目的模型选型复盘
人工智能·gpt·算法
江屿风13 分钟前
C++图论基础Bellman-Ford与spfa算法如何判断负环
开发语言·c++·笔记·算法·图论
YHHLAI15 分钟前
LeetCode 136.只出现一次的数字 | 从遍历统计到位运算极致优化
算法·leetcode·职场和发展
lihao lihao23 分钟前
Linux线程同步与互斥
linux·数据结构·算法
进击的荆棘31 分钟前
优选算法——BFS
c++·算法·leetcode·宽度优先
南境十里·墨染春水9 小时前
C++ 工厂模式:从入门到进阶,彻底掌握对象创建的艺术
开发语言·c++·算法
@insist1239 小时前
系统架构设计师-实时性评价、调度算法与内核架构选型
算法·架构·系统架构·软考·系统架构设计师·软件水平考试