[LeetCode] 994. Rotting Oranges

腐烂的橘子。题意是给一个二维数组,用几个数字分别表示橘子的腐烂情况。每过去一分钟,任何腐烂的橘子的上下左右四个方向上的新鲜橘子都会腐烂。请求出全部橘子腐烂需要的分钟数,如果不会全都腐烂,则返回-1。

0 代表空单元格;

1 代表新鲜橘子;

2 代表腐烂的橘子。

例子,

Example 1:
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4

Example 2:
Input: [[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: [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.

这是一个BFS的基本题。需要用queue去记录每个cell四周的四个cell在被更新过之后的腐烂情况。

时间O(mn)

空间O(mn)

 1 /**
 2  * @param {number[][]} grid
 3  * @return {number}
 4  */
 5 var orangesRotting = function (grid) {
 6     let q = [];
 7     let newFresh = 0;
 8     let minutes = 0;
 9     // push rotten oranges to the stack and count fresh oranges
10     for (let i = 0; i < grid.length; i++) {
11         for (let j = 0; j < grid[i].length; j++) {
12             if (grid[i][j] === 2) q.push([i, j]);
13             if (grid[i][j] === 1) newFresh++;
14         }
15     }
16 
17     while (q.length && newFresh) {
18         let newQ = []; // queue for next minute
19         while (q.length) {
20             let badOrange = q.shift();
21             let newRottens = infectOthers(grid, badOrange[0], badOrange[1], newQ);
22             newFresh -= newRottens;
23         }
24         minutes++;
25         q = newQ;
26     }
27     if (newFresh !== 0) return -1;
28     return minutes;
29 };
30 
31 // Infect surrounding oranges
32 // Return the number of newly infected oranges
33 var infectOthers = function (grid, i, j, q) {
34     let infected = 0;
35     if (i > 0 && grid[i - 1][j] === 1) {
36         grid[i - 1][j]++;
37         infected++;
38         q.push([i - 1, j]);
39     }
40     if (j > 0 && grid[i][j - 1] === 1) {
41         grid[i][j - 1]++;
42         infected++;
43         q.push([i, j - 1]);
44     }
45     if (i < grid.length - 1 && grid[i + 1][j] === 1) {
46         grid[i + 1][j]++;
47         infected++;
48         q.push([i + 1, j]);
49     }
50     if (j < grid[0].length - 1 && grid[i][j + 1] === 1) {
51         grid[i][j + 1]++;
52         infected++;
53         q.push([i, j + 1]);
54     }
55     return infected;
56 }

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/12408644.html
今日推荐