class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
res = [[None for _ in range(len(matrix[0]))] for _ in range(len(matrix))] # 设定结果集
q = collections.deque()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
res[i][j] = 0
q.append([i, j])
while q:
x, y = q.popleft()
for x_bias, y_bias in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
new_x = x + x_bias
new_y = y + y_bias
if 0 <= new_x < len(matrix) and 0 <= new_y < len(matrix[0]) and res[new_x][new_y] == None:
res[new_x][new_y] = res[x][y] + 1
q.append([new_x, new_y])
return res
leetcode-542 01矩阵 Python
最新推荐文章于 2020-07-28 10:38:59 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)