LeetCode 994. Rotting Oranges
原题链接在这里:https://leetcode.com/problems/rotting-oranges/
题目:
In a given grid, each cell can have one of three values:
- the value
0
representing an empty cell; - the value
1
representing a fresh orange; - the value
2
representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) 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
instead.
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.
Note:
1 <= grid.length <= 10
1 <= grid[0].length <= 10
grid[i][j]
is only0
,1
, or2
.
题解:
Iterate grid, for rotten orange, add it to the queue, for fresh orange, count++.
Perform BFS, when neibor is fresh, mark it as rotton and add to que, count--.
If eventually count == 0, then all rotton. return level.
Note: pay attention to corner case. [[0]], at the beginning, count == 0, return 0.
Time Complexity: O(m * n). m = grid.length. n = grid[0].length.
Space: O(m * n).
AC Java:
1 class Solution { 2 public int orangesRotting(int[][] grid) { 3 if(grid == null || grid.length == 0 || grid[0].length == 0){ 4 return 0; 5 } 6 7 int m = grid.length; 8 int n = grid[0].length; 9 int count = 0; 10 LinkedList<int []> que = new LinkedList<>(); 11 int [][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; 12 for(int i = 0; i < m; i++){ 13 for(int j = 0; j < n; j++){ 14 if(grid[i][j] == 2){ 15 que.add(new int[]{i, j}); 16 }else if(grid[i][j] == 1){ 17 count++; 18 } 19 } 20 } 21 22 if(count == 0){ 23 return 0; 24 } 25 26 int level = -1; 27 while(!que.isEmpty()){ 28 int size = que.size(); 29 while(size-- > 0){ 30 int [] cur = que.poll(); 31 for(int [] dir : dirs){ 32 int x = cur[0] + dir[0]; 33 int y = cur[1] + dir[1]; 34 if(x < 0 || x >= m || y < 0 || y >= n || grid[x][y] != 1){ 35 continue; 36 } 37 38 que.add(new int[]{x, y}); 39 grid[x][y] = 2; 40 count--; 41 } 42 } 43 44 level++; 45 } 46 47 return count == 0? level : -1; 48 } 49 }