nathanwailes

LeetCode 994 - Rotting Oranges - 2022.12.30 solution

Dec 31st, 2022
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | None | 0 0
  1. class Solution:
  2.     def orangesRotting(self, grid: List[List[int]]) -> int:
  3.         """ How to solve it: First iterate through every cell to find all the rotting oranges, and add them
  4.        to a deque.  Also count the fresh oranges.
  5.        Then do repeated iterations through the length of the deque (at the time of the start of the
  6.        iteration) to pop each rotting orange, add its fresh-orange neighbors to the end of the deque,
  7.        decrement the count of fresh oranges, and increment the minute-counter.
  8.        When the deque is empty, if the count of fresh oranges is still greater than 0, return -1, else return
  9.        the number of minutes passed.
  10.        """
  11.         fresh_oranges = 0
  12.         ROWS = len(grid)
  13.         COLS = len(grid[0])
  14.         rotting_oranges = deque()
  15.         minutes = -1
  16.         for r in range(ROWS):
  17.             for c in range(COLS):
  18.                 val = grid[r][c]
  19.                 if val == 1:
  20.                     fresh_oranges += 1
  21.                 elif val == 2:
  22.                     rotting_oranges.append((r, c))
  23.        
  24.         visited = set()
  25.         while rotting_oranges:
  26.             minutes += 1
  27.             for i in range(len(rotting_oranges)):
  28.                 rotten_orange = rotting_oranges.popleft()
  29.                 grid[rotten_orange[0]][rotten_orange[1]] = 2
  30.                 adjustments = [
  31.                     [0, 1,],
  32.                     [0, -1],
  33.                     [1, 0],
  34.                     [-1, 0],
  35.                 ]
  36.                 neighbors = [(rotten_orange[0] + a[0], rotten_orange[1] + a[1]) for a in adjustments]
  37.                 for neighbor in neighbors:
  38.                     if neighbor[0] < 0 or neighbor[0] >= ROWS or \
  39.                        neighbor[1] < 0 or neighbor[1] >= COLS:
  40.                        continue
  41.                     elif grid[neighbor[0]][neighbor[1]] != 1:
  42.                         continue
  43.                     elif neighbor in visited:
  44.                         continue
  45.                     visited.add(neighbor)
  46.                     fresh_oranges -= 1
  47.                     rotting_oranges.append(neighbor)
  48.         if fresh_oranges > 0:
  49.             return -1
  50.         return max(0, minutes)
Advertisement
Add Comment
Please, Sign In to add comment