Untitled
unknown
python
2 years ago
831 B
9
Indexable
from collections import deque
# initialize variables
matrix = [row[:] for row in mat]
rows = len(matrix)
cols = len(matrix[0])
q = deque()
seen = set()
# initialize queue
for row in range(rows):
for col in range(cols):
if matrix[row][col] == 0:
q.append((row, col, 0))
seen.add((row, col))
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
# perform bfs
while q:
# pop next node
row, col, steps = q.popleft()
# traverse neighbors
for dx, dy in directions:
next_row, next_col = row + dy, col + dx
# perform logic
if (next_row, next_col) not in seen and valid(next_row, next_col):
seen.add((next_row, next_col))
q.append((next_row, next_col, steps + 1))
matrix[next_row][next_col] = steps + 1
return matrixEditor is loading...
Leave a Comment