Faaez Razeen

Rotting Oranges

  • 2 min read
  • Graph
  • LC-Medium

3 years ago

Solution

TimeSpaceExplanation
O(mn)O(mn)
def orangesRotting(self, grid: List[List[int]]) -> int: nrows, ncols = len(grid), len(grid[0]) num_oranges = num_rotten = minutes = 0 q = deque() for r in range(nrows): for c in range(ncols): if grid[r][c] == 2: q.append((r, c)) if grid[r][c] > 0: num_oranges += 1 while q: for _ in range(len(q)): r, c = q.popleft() num_rotten += 1 for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]: nr, nc = r + dr, c + dc if nr >= 0 and nr < nrows and nc >= 0 and nc < ncols and grid[nr][nc] == 1: grid[nr][nc] = 2 q.append((nr, nc)) if q: minutes += 1 return minutes if num_rotten == num_oranges else -1