Advertisement
serega1112

994

Mar 7th, 2021
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.82 KB | None | 0 0
  1. class Solution:
  2.     def orangesRotting(self, grid: List[List[int]]) -> int:
  3.         step = 0
  4.         q = []
  5.         for i in range(len(grid)):
  6.             for j in range(len(grid[0])):
  7.                 if grid[i][j] == 2:
  8.                     q.append((i, j, step))
  9.                    
  10.         while q:
  11.             x, y, step = q.pop(0)
  12.             for xp, yp in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:
  13.                 if 0 <= xp < len(grid) and 0 <= yp < len(grid[0]):
  14.                     if grid[xp][yp] == 1:
  15.                         q.append((xp, yp, step + 1))
  16.                         grid[xp][yp] = 2
  17.                        
  18.        
  19.         for i in range(len(grid)):
  20.             for j in range(len(grid[0])):
  21.                 if grid[i][j] == 1:
  22.                     return -1
  23.                
  24.         return step
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement