smj007

Rotten Oranges

Jul 29th, 2025
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. class Solution:
  2.     def orangesRotting(self, grid: List[List[int]]) -> int:
  3.  
  4.         q = deque()
  5.         n, m = len(grid), len(grid[0])
  6.         fresh = 0
  7.         rotten = 0
  8.         level = 0
  9.  
  10.         for i in range(n):
  11.             for j in range(m):
  12.                 if grid[i][j] == 2:
  13.                     q.append((i, j))
  14.                 if grid[i][j] == 1:
  15.                     fresh += 1
  16.  
  17.         while q:
  18.             for _ in range(len(q)):
  19.                 (r, c) = q.popleft()
  20.  
  21.                 directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
  22.                 for (dr, dc) in directions:
  23.                     row, col = r + dr, c + dc
  24.  
  25.                     if row in range(n) and col in range(m) and grid[row][col] == 1:
  26.                         q.append((row, col))
  27.                         grid[row][col] = 2
  28.                         rotten += 1
  29.  
  30.             if q:
  31.                 level += 1
  32.  
  33.         return level if fresh==rotten else -1
  34.  
Advertisement
Add Comment
Please, Sign In to add comment