力扣HOT100 - 994. 腐烂的橘子

文章描述了一种算法,用于解决在一个二维网格中,新鲜橘子被腐烂橘子影响腐烂的问题。通过广度优先搜索和队列操作,计算新鲜橘子完全腐烂所需的最小分钟数。
摘要由CSDN通过智能技术生成

解题思路:

因为要记录轮数(分钟数),所以不能一口气遍历到底,所以不能用深搜(bfs),而要用广搜(bfs,层序遍历)。

先记录下新鲜橘子数,并用一个队列记录腐烂橘子的坐标。

每轮遍历腐烂橘子(使用过的腐烂橘子需要出队),并向四周影响,使得四周的新鲜橘子变为腐烂橘子(新鲜橘子数减1,队列中加入新的腐烂橘子的坐标)。

class Solution {
    public int orangesRotting(int[][] grid) {
        Queue<int[]> queue = new LinkedList<>();
        int fresh = 0;
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[0].length; c++) {
                if (grid[r][c] == 1) fresh++;
                else if (grid[r][c] == 2) queue.add(new int[] { r, c });
            }
        }

        int minutes = 0;
        while (fresh > 0 && !queue.isEmpty()) {
            minutes++;
            int n = queue.size();// for循环中queue大小不断变化,需要提前暂存
            for (int i = 0; i < n; i++) {
                int[] orange = queue.poll();
                int r = orange[0];
                int c = orange[1];
                if (r - 1 >= 0 && grid[r - 1][c] == 1) {
                    grid[r - 1][c] = 2;
                    fresh--;
                    queue.add(new int[] { r - 1, c });
                }
                if (r + 1 < grid.length && grid[r + 1][c] == 1) {
                    grid[r + 1][c] = 2;
                    fresh--;
                    queue.add(new int[] { r + 1, c });
                }
                if (c - 1 >= 0 && grid[r][c - 1] == 1) {
                    grid[r][c - 1] = 2;
                    fresh--;
                    queue.add(new int[] { r, c - 1 });
                }
                if (c + 1 < grid[0].length && grid[r][c + 1] == 1) {
                    grid[r][c + 1] = 2;
                    fresh--;
                    queue.add(new int[] { r, c + 1 });
                }
            }
        }
        if (fresh > 0) return -1;
        else return minutes;
    }
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值