Skip to content

Commit

Permalink
Merge pull request #68 from s2gh/patch-15
Browse files Browse the repository at this point in the history
Create 13. Walls and Gates.py
  • Loading branch information
SamirPaulb authored Mar 2, 2024
2 parents f463214 + aee68c8 commit d5d220b
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions 07_Graph/13. Walls and Gates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# https://www.lintcode.com/problem/663

from typing import List
import collections

class Solution:
def walls_and_gates(self, rooms: List[List[int]]):
row, col = len(rooms), len(rooms[0])
EMPTY, GATE = 2*31-1, 0
q = collections.deque()
for i in range(row):
for j in range(col):
if rooms[i][j] == GATE:
q.append((i,j))
while q:
i,j = q.popleft()
for dx,dy in (1,0), (-1,0), (0,1), (0,-1):
x,y = i+dx, j+dy
if 0<=x<row and 0<=y<col and rooms[i][j] + 1 < rooms[x][y]:
rooms[x][y] = rooms[i][j] + 1
q.append((x,y))

# Time: O(row * col)
# Space: O(cnt_GATE + cnt_EMPTY)

0 comments on commit d5d220b

Please sign in to comment.