简单多源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;
    }
};
相关推荐
geovindu7 分钟前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
Zachery Pole2 小时前
CCF-CSP备战NO.7【队列】
算法
闪电悠米2 小时前
力扣hot100-48.旋转图像-转置翻转详解
算法·leetcode·职场和发展
满天星83035773 小时前
【算法】最长递增子序列(三种解法)
算法
啦啦啦啦啦zzzz3 小时前
算法:贪心算法
c++·算法·leetcode·贪心算法
清泓y5 小时前
RAG 技术
算法·ai
阿慧今天瘦了嘛5 小时前
计算机组成原理概述:从硬件到软件的桥梁
计算机网络·算法
网站优化(SEO)专家6 小时前
SEO核心算法拆解:网站排名快速提升的武林秘籍!
算法·搜索引擎·网站排名·核心算法
惊讶的猫6 小时前
CLGSI
人工智能·算法·机器学习
无限码力7 小时前
华为非AI方向笔试真题 7月15号【字符补全】
算法·华为·华为笔试真题·华为非ai笔试真题·华为笔试·华为笔试非ai真题