python
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
# 思路是bfs,使用队列控制腐烂橘子的进出,然后在while循环末位对结果进行控制
if not grid or len(grid)==0:
return -1
def check_zeros(array):
for row in array:
for elem in row:
if elem != 0:
return False
return True
myflag=check_zeros(grid)
if myflag:
return 0
que=collections.deque()
result=0
row=len(grid)
col=len(grid[0])
for i in range(row):
for j in range(col):
if grid[i][j]==2:
que.append([i,j])
if (
(i-1<0 or grid[i-1][j]==0) and
(j-1<0 or grid[i][j-1]==0) and
(i+1>=row or grid[i+1][j]==0) and
(j+1>=col or grid[i][j+1]==0) and
grid[i][j]==1
):
return -1
if not que:
return -1
while que:
size=len(que)
result+=1
while size:
cur=que.popleft()
x=cur[0]
y=cur[1]
if x-1>=0 and grid[x-1][y]==1:
que.append([x-1,y])
grid[x-1][y]=2
if y-1>=0 and grid[x][y-1]==1:
que.append([x,y-1])
grid[x][y-1]=2
if x+1<row and grid[x+1][y]==1:
que.append([x+1,y])
grid[x+1][y]=2
if y+1<col and grid[x][y+1]==1:
que.append([x,y+1])
grid[x][y+1]=2
size-=1
return result-1
思路:
- bfs,使用队列维护,使用reslut控制结果
- 我自己写的这个打了很多补丁,然后还是有很多条件没有考虑到,但大体上bfs的思路是正确的
官方题解(也是bfs,而且多源我也考虑到了):
python
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
R, C = len(grid), len(grid[0])
# queue - all starting cells with rotting oranges
queue = collections.deque()
for r, row in enumerate(grid):
for c, val in enumerate(row):
if val == 2:
queue.append((r, c, 0))
def neighbors(r, c) -> (int, int):
for nr, nc in ((r - 1, c), (r, c - 1), (r + 1, c), (r, c + 1)):
if 0 <= nr < R and 0 <= nc < C:
yield nr, nc
d = 0
while queue:
r, c, d = queue.popleft()
for nr, nc in neighbors(r, c):
if grid[nr][nc] == 1:
grid[nr][nc] = 2
queue.append((nr, nc, d + 1))
if any(1 in row for row in grid):
return -1
return d