Advertisement
smj007

Untitled

Aug 20th, 2023
590
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.04 KB | None | 0 0
  1. class Solution:
  2.     def orangesRotting(self, grid: List[List[int]]) -> int:
  3.         rows, cols = len(grid), len(grid[0])
  4.         q = collections.deque()
  5.         time = 0
  6.         total_fresh = 0
  7.         count_fresh = 0
  8.  
  9.         for r in range(rows):
  10.             for c in range(cols):
  11.                 if grid[r][c] == 1:
  12.                     total_fresh += 1
  13.                 if grid[r][c] == 2:
  14.                     q.append((r, c))
  15.  
  16.         directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
  17.         while(q) and total_fresh!=count_fresh:
  18.             size = len(q)
  19.             for _ in range(size):
  20.                 r, c = q.popleft()
  21.                 for dr, dc in directions:
  22.                     row = r + dr
  23.                     col = c + dc
  24.                     if row in range(rows) and col in range(cols) and grid[row][col] == 1:
  25.                         grid[row][col] = 2
  26.                         q.append((row, col))
  27.                         count_fresh += 1
  28.             time = time + 1
  29.  
  30.         return -1 if total_fresh!=count_fresh else time
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement