mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-07-26 08:15:27 -04:00
Update matrix_bfs.py
This commit is contained in:
parent
93a6452f57
commit
d574e9627d
1 changed files with 5 additions and 15 deletions
|
@ -2,18 +2,8 @@
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
# author: bt3gl
|
# author: bt3gl
|
||||||
|
|
||||||
'''
|
|
||||||
You are given an m x n grid rooms initialized with these three possible values.
|
|
||||||
|
|
||||||
* -1 A wall or an obstacle.
|
def matrix_bfs(rooms) -> None:
|
||||||
* 0 A gate.
|
|
||||||
* INF Infinity means an empty room (2^31 - 1 = 2147483647 to represent INF)
|
|
||||||
|
|
||||||
Fill each empty room with the distance to its nearest gate.
|
|
||||||
If it is impossible to reach a gate, it should be filled with INF.
|
|
||||||
'''
|
|
||||||
|
|
||||||
def matrix_bfs(rooms: list[list[int]]) -> None:
|
|
||||||
|
|
||||||
m = len(rooms)
|
m = len(rooms)
|
||||||
if m == 0:
|
if m == 0:
|
||||||
|
@ -24,7 +14,7 @@ def matrix_bfs(rooms: list[list[int]]) -> None:
|
||||||
EMPTY = 2147483647
|
EMPTY = 2147483647
|
||||||
DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1))
|
DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1))
|
||||||
|
|
||||||
q = collections.deque()
|
queue = collections.deque()
|
||||||
|
|
||||||
for i in range(m):
|
for i in range(m):
|
||||||
for j in range(n):
|
for j in range(n):
|
||||||
|
@ -32,9 +22,9 @@ def matrix_bfs(rooms: list[list[int]]) -> None:
|
||||||
if rooms[i][j] == GATE:
|
if rooms[i][j] == GATE:
|
||||||
q.append((i, j))
|
q.append((i, j))
|
||||||
|
|
||||||
while q:
|
while queue:
|
||||||
|
|
||||||
row, col = q.popleft()
|
row, col = queue.popleft()
|
||||||
|
|
||||||
for (x, y) in DIRECTIONS:
|
for (x, y) in DIRECTIONS:
|
||||||
|
|
||||||
|
@ -45,4 +35,4 @@ def matrix_bfs(rooms: list[list[int]]) -> None:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
rooms[r][c] = rooms[row][col] + 1
|
rooms[r][c] = rooms[row][col] + 1
|
||||||
q.append((r, c))
|
queue.append((r, c))
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue