smj007

Walls and Gates

Jul 29th, 2025
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. class Solution(object):
  2.     def wallsAndGates(self, rooms):
  3.         """
  4.        :type rooms: List[List[int]]
  5.        :rtype: None Do not return anything, modify rooms in-place instead.
  6.        """
  7.        
  8.  
  9.         from collections import deque
  10.  
  11.         INF = 2147483647
  12.  
  13.         q = deque()
  14.  
  15.         n, m = len(rooms), len(rooms[0])
  16.         for i in range(n):
  17.             for j in range(m):
  18.                 if rooms[i][j] == 0:
  19.                     q.append((i, j))
  20.  
  21.         count = 1
  22.         while q:
  23.             row, col = q.popleft()
  24.  
  25.             directions = [
  26.                 (row+1, col),
  27.                 (row-1, col),
  28.                 (row, col+1),
  29.                 (row, col-1)
  30.             ]
  31.  
  32.             for (r, c) in directions:
  33.                 if r in range(n) and c in range(m) and rooms[r][c] == INF:
  34.                     q.append((r, c))
  35.                     rooms[r][c] = rooms[row][col] + 1
  36.  
  37.             count += 1
Advertisement
Add Comment
Please, Sign In to add comment