简单多源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;
    }
};
相关推荐
听取WA声一片(无恶意)17 小时前
CSP-J/S 初赛图论完全讲义
算法·csp-s初赛·csp-j初赛
Brilliantwxx17 小时前
【算法从零到千】【51-54】逆序对(分治+递归算法)
数据结构·算法·排序算法
小星星闪亮登场17 小时前
2026河南萌新联赛第四场--南阳理工学院
数据结构·算法·贪心算法·动态规划·哈希算法·广度优先
土司大王17 小时前
LeetCode hot100——两数之和
数据结构·算法·leetcode
luj_176818 小时前
大航海时代:沉浸式财商实战沙盒
c语言·开发语言·网络·经验分享·算法
Navigator_Z18 小时前
LeetCode //C - 1200. Minimum Absolute Difference
c语言·算法·leetcode
wabs66618 小时前
关于字符串【力扣344.反转字符串的思考】
数据结构·算法·leetcode
民乐团扒谱机19 小时前
【微实验】谐波乘积谱(HPS)算法深度解析:原理、数学与代码实现
开发语言·人工智能·python·算法·语音识别·音乐
Nil20819 小时前
leetcode 73矩阵置0
算法·leetcode·矩阵
luj_176821 小时前
财商游戏三大核心维度设计
c语言·开发语言·网络·经验分享·算法