topic:
“””
Given m x n
grid
grid
middle,Each cell can have one of the following three values:
- value
0
Represents the empty unit; - value
1
Represents fresh oranges; - value
2
代表Rotten orange。
every minute,Rotten orange around 4 Adjacent in this direction Fresh oranges will rot。
return 直到单元格middle没有新鲜橘子为止所必须经过的最小分钟数。If it is impossible,return -1
。
Exemplary example 1:
enter:grid = [[2,1,1],[1,1,0],[0,1,1]] Output:4
Exemplary example 2:
enter:grid = [[2,1,1],[0,1,1],[1,0,1]] Output:-1 explain:Orange in the lower left corner(First 2 OK, First 0 List)Never rot,Because rotten will only happen in 4 In the direction。
Exemplary example 3:
enter:grid = [[0,2]] Output:0 explain:because 0 There is no fresh orange in minutes,So the answer is 0 。
hint:
m == grid.length
n == grid[i].length
1 <= m, n <= 10
grid[i][j]
Only for0
、1
or2
Thought:
这个问题可以用Priority search(BFS)To solve。We need to track the spread of rotten oranges,Record time,And check if there is a fresh orange that cannot be rotten。The initial idea of the original idea:
1 | class Solution: |
Similar to multi -threaded,每个线程存入一个初始队List,初始队List通过BFSGradual diffusion
Code:
1 | from collections import deque |
1 | import ( |