简单多源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;
    }
};
相关推荐
curry____30335 分钟前
study in PTA(高精度算法与预处理)(2025.12.3)
数据结构·c++·算法·高精度算法
ChoSeitaku41 分钟前
高数强化NO6|极限的应用|连续的概念性质|间断点的定义分类|导数与微分
人工智能·算法·分类
代码游侠1 小时前
学习笔记——栈
开发语言·数据结构·笔记·学习·算法
自然语1 小时前
人工智能之数字生命-情绪
人工智能·算法
Ayanami_Reii1 小时前
进阶数据结构应用-维护序列
数据结构·算法·线段树
_w_z_j_1 小时前
mari和shiny() (多状态dp数组)
算法
CoderYanger1 小时前
C.滑动窗口-越长越合法/求最短/最小——2904. 最短且字典序最小的美丽子字符串
java·开发语言·数据结构·算法·leetcode·1024程序员节
Tim_101 小时前
【算法专题训练】33、堆
算法
Salt_07281 小时前
DAY25 奇异值SVD分解
python·算法·机器学习