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
最新推荐文章于 2021-10-11 16:34:11 发布
本文介绍了如何使用Python解决LeetCode中的542题——01矩阵问题。通过深入解析算法思路,展示了如何遍历矩阵并更新其元素,最终得到所需的01转换矩阵。
部署运行你感兴趣的模型镜像
您可能感兴趣的与本文相关的镜像
Python3.9
Conda
Python
Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本
528

被折叠的 条评论
为什么被折叠?



