简单多源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;
    }
};
相关推荐
m0_7482500342 分钟前
C++ 信号处理
c++·算法·信号处理
Ro Jace43 分钟前
电子侦察信号处理流程及常用算法
算法·信号处理
yuyanjingtao1 小时前
动态规划 背包 之 凑钱
c++·算法·青少年编程·动态规划·gesp·csp-j/s
core5122 小时前
SGD 算法详解:蒙眼下山的寻宝者
人工智能·算法·矩阵分解·sgd·目标函数
Ka1Yan2 小时前
[链表] - 代码随想录 707. 设计链表
数据结构·算法·链表
scx201310042 小时前
20260112树状数组总结
数据结构·c++·算法·树状数组
FastMoMO2 小时前
Qwen3-VL-2B 在 RK3576 上的部署实践:RKNN + RKLLM 全流程
算法
光算科技2 小时前
AI重写工具导致‘文本湍流’特征|如何人工消除算法识别标记
大数据·人工智能·算法
宵时待雨2 小时前
数据结构(初阶)笔记归纳3:顺序表的应用
c语言·开发语言·数据结构·笔记·算法
智者知已应修善业2 小时前
【C语言 dfs算法 十四届蓝桥杯 D飞机降落问题】2024-4-12
c语言·c++·经验分享·笔记·算法·蓝桥杯·深度优先