542. 01 Matrix
难度:Medium
- 直接以所有 0 位置为起点进行 BFS 遍历即可
- 为了减小空间常数,使用 cur, nxt 两个 list,而不是一开始开一个长为元素个数 m×n 的 list 来模拟队列
- 时间复杂度
class Solution:
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
m = len(mat)
n = len(mat[0])
dis = []
for i in range(m):
dis.append([-1] * n)
head = 0
tail = 0
cur = []
nxt = []
for i in range(m):
for j in range(n):
if mat[i][j] == 0:
dis[i][j] = 0
cur.append((i, j))
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
while cur:
nxt.clear()
for x, y in cur:
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if nx < 0 or nx >= m or ny < 0 or ny >= n or dis[nx][ny] != -1:
continue
dis[nx][ny] = dis[x][y] + 1
nxt.append((nx, ny))
cur.clear()
for coord in nxt:
cur.append(coord)
return dis