LeetCode 994 Rotting Oranges (bfs 推荐)

244 篇文章 0 订阅
16 篇文章 0 订阅

You are given an m x n grid where each cell can have one of three values:

  • 0 representing an empty cell,
  • 1 representing a fresh orange, or
  • 2 representing a rotten orange.

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

Example 1:

Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4

Example 2:

Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.

Example 3:

Input: grid = [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 10
  • grid[i][j] is 01, or 2.

题目链接:https://leetcode.com/problems/rotting-oranges/

题目大意:有一些烂橘子,没秒会使上下左右的橘子变烂,问需要多少秒可以使所有橘子变烂,若不可能输出-1

题目分析:有点类似二叉树的分层遍历,每秒将当前的烂橘子向四个方向延伸即可,bfs完再判断是否还存在好橘子

3ms,时间击败64.85%

class Solution {
    
    class RottenOrange {
        int x, y;
        RottenOrange(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
    
    private final int[] dx = new int[] {0, 1, 0, -1};
    private final int[] dy = new int[] {1, 0, -1, 0};
    
    public int orangesRotting(int[][] grid) {
        int n = grid.length, m = grid[0].length;
        Queue<RottenOrange> q = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 2) {
                    q.offer(new RottenOrange(i, j));
                }
            }
        }
        int cnt = 0;
        while (!q.isEmpty()) {
            int sz = q.size();
            cnt++;
            for (int i = 0; i < sz; i++) {
                RottenOrange ro = q.poll();
                for (int j = 0; j < 4; j++) {
                    int nx = ro.x + dx[j];
                    int ny = ro.y + dy[j];
                    if (nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] == 1) {
                        grid[nx][ny] = 2;
                        q.offer(new RottenOrange(nx, ny));
                    }
                }
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 1) {
                    return -1;
                }
            }
        }
        return cnt == 0 ? 0 : cnt - 1;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值