简单多源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;
    }
};
相关推荐
kebidaixu29 分钟前
两轮BMS 短路保护策略详解
算法
zwenqiyu1 小时前
非线性字符串数据结构串讲
数据结构·c++·学习·算法
z小猫不吃鱼1 小时前
03 Optimal Brain Surgeon 详解:Hessian 剪枝为什么有效?
算法·机器学习·剪枝
硕风和炜1 小时前
【LeetCode: 1301. 最大得分的路径数目 + DP】
java·算法·leetcode·动态规划·dp·记忆化搜索
用户99045017780091 小时前
做了一个AI诊断,参考倪海厦中医理论,科学养生
算法
努力中的编程者2 小时前
STL-vector的模拟实现
开发语言·c++·算法·stl·vector
weixin_400005602 小时前
RL-frenet-trajectory-planning-in-CARLA
人工智能·深度学习·算法·机器学习·自动驾驶
Keven_112 小时前
AcWing算法提高课思路速查:动态规划
算法·动态规划
剑挑星河月2 小时前
94.二叉树的中序遍历
java·算法·leetcode
拳里剑气2 小时前
C++算法:队列与BFS
c++·算法·bfs·宽度优先·队列