classSolution(object): deforangesRotting(self, A): R, C = len(A), len(A[0])
# queue - all starting cells with rotting oranges queue = collections.deque() for r, row in enumerate(A): for c, val in enumerate(row): if val == 2: queue.append((r, c, 0))
defneighbors(r, c): for nr, nc in ((r-1,c),(r,c-1),(r+1,c),(r,c+1)): if0 <= nr < R and0 <= nc < C: yield nr, nc
d = 0 while queue: r, c, d = queue.popleft() for nr, nc in neighbors(r, c): if A[nr][nc] == 1: A[nr][nc] = 2 queue.append((nr, nc, d+1))