Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import deque
- class Solution:
- def orangesRotting(self, grid):
- q = deque()
- row, col = len(grid), len(grid[0])
- check = [[False for _ in range(col)] for _ in range(row)]
- total_fresh = 0
- ans = 0
- for i in range(row):
- for j in range(col):
- if grid[i][j] == 2:
- q.append((i, j))
- check[i][j] = True
- if grid[i][j] == 1:
- total_fresh += 1
- while len(q) and total_fresh:
- k = len(q)
- x = [-1, 0, 1, 0]
- y = [0, 1, 0, -1]
- for i in range(k):
- temp = q[0]
- q.popleft()
- for k in range(4):
- new_x = temp[0] + x[k]
- new_y = temp[1] + y[k]
- if (new_x >= 0 and new_y >= 0 and new_x < row and new_y < col
- and grid[new_x][new_y] == 1 and not check[new_x][new_y]):
- q.append((new_x, new_y))
- check[new_x][new_y] = True
- total_fresh -= 1
- ans += 1
- if total_fresh != 0:
- return -1
- return ans
Advertisement
Add Comment
Please, Sign In to add comment