有不足之处请多多指教
BFS模板:
#(1).不需要确定当前遍历到了哪一层
dirs = [[1,0],[-1,0],[0,-1],[0,1]]
while queue:
point = queue.pop(0)
for 节点 in cur的所有相邻节点:
if 该节点有效且未访问过:
queue.append(该节点)
#(2).需要确定当前遍历到了哪一层
dirs = [[1,0],[-1,0],[0,-1],[0,1]]
level = 0
while queue 不空:
size = queue.size()
for i in range(size)
cur = queue.pop(0)
for 节点 in cur的所有相邻节点:
if 该节点有效且未被访问过:
queue.append(该节点)
level += 1
本题需要确定遍历的层次
即题中:全部腐烂需要几分钟
代码
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
lenx, leny = len(grid), len(grid[0])
dirs = [[1,0],[-1,0],[0,1],[0,-1]] #每次腐烂是按照上下左右四个方向进行
queue = []
fresh = 0
for i in range(lenx):
for j in range(leny):
if grid[i][j] == 2:
queue.append([i,j]) #初始化队列中元素
if grid[i][j] == 1:
fresh += 1 #新鲜橘子的个数
if fresh == 0: return 0
leval = 0 #分钟数
while queue and fresh > 0: #套用模板
size = len(queue)
for i in range(size):
x, y = queue.pop(0)
#向四个方向腐烂
for dirx,diry in dirs:
newx, newy = x + dirx, y + diry
#符合范围且橘子还是新鲜的(1)执行将坐标加入队列并将橘子变为腐烂(0)
#同时新鲜橘子数目-1
if 0 <= newx < lenx and 0 <= newy < leny and grid[newx][newy] == 1:
grid[newx][newy] = 2
queue.append([newx,newy])
fresh -= 1
leval += 1
if fresh > 0: #如果还有橘子腐烂不了,即题中的不可能使所有橘子腐烂,返回-1
return -1
else:
return leval