其他分享
首页 > 其他分享> > [LeetCode] 994. Rotting Oranges 腐烂的橘子

[LeetCode] 994. Rotting Oranges 腐烂的橘子

作者:互联网


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

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:


这道题说给的一个 mxn 大小的格子上有些新鲜和腐烂的橘子,每一分钟腐烂的橘子都会传染给其周围四个中的新鲜橘子,使得其也变得腐烂。现在问需要多少分钟可以使得所有的新鲜橘子都变腐烂,无法做到时返回 -1。由于这里新鲜的橘子自己不会变腐烂,只有被周围的腐烂橘子传染才会,所以当新鲜橘子周围不会出现腐烂橘子的时候,那么这个新鲜橘子就不会腐烂,这才会有返回 -1 的情况。这道题就是个典型的广度优先遍历 Breadth First Search,并没有什么太大的难度,先遍历一遍整个二维数组,统计出所有新鲜橘子的个数,并把腐烂的橘子坐标放入一个队列 queue,之后进行 while 循环,循环条件是队列不会空,且 freshLeft 大于0,使用层序遍历的方法,用个 for 循环在内部。每次取出队首元素,遍历其周围四个位置,越界或者不是新鲜橘子都跳过,否则将新鲜橘子标记为腐烂,加入队列中,并且 freshLeft 自减1。每层遍历完成之后,结果 res 自增1,最后返回的时候,若还有新鲜橘子,即 freshLeft 大于0时,返回 -1,否则返回 res 即可,参见代码如下:


class Solution {
public:
    int orangesRotting(vector<vector<int>>& grid) {
        int res = 0, m = grid.size(), n = grid[0].size(), freshLeft = 0;
        queue<vector<int>> q;
        vector<vector<int>> dirs{{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 1) ++freshLeft;
                else if (grid[i][j] == 2) q.push({i, j});
            }
        }
        while (!q.empty() && freshLeft > 0) {
            for (int i = q.size(); i > 0; --i) {
                auto cur = q.front(); q.pop();
                for (int k = 0; k < 4; ++k) {
                    int x = cur[0] + dirs[k][0], y = cur[1] + dirs[k][1];
                    if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] != 1) continue;
                    grid[x][y] = 2;
                    q.push({x, y});
                    --freshLeft;
                }
            }
            ++res;
        }
        return freshLeft > 0 ? -1 : res;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/994


类似题目:

Walls and Gates


参考资料:

https://leetcode.com/problems/rotting-oranges/

https://leetcode.com/problems/rotting-oranges/discuss/238681/Java-Clean-BFS-Solution-with-comments


LeetCode All in One 题目讲解汇总(持续更新中...)

标签:994,Rotting,Oranges,腐烂,int,grid,新鲜,橘子,freshLeft
来源: https://www.cnblogs.com/grandyang/p/14257283.html