题目
给定一个由0和1组成的矩阵,找出每个元素到最近的0的距离。
两个相邻元素间的距离为1。
思路
最短距离——广度优先搜索bfs。
class Solution:
def updateMatrix(self, matrix):
if len(matrix) == 0 or len(matrix[0]) == 0: return matrix
def bfs(ans, row, col):
# 广搜找到距离最近0的距离
step = 0
queue = [(row, col)]
while len(queue) != 0:
for x, y in queue[:]:
if matrix[x][y] == 0:
ans[row][col] = step
return
if 0 <= x - 1 < rows:
queue.append((x - 1, y))
if 0 <= x + 1 < rows:
queue.append((x + 1, y))
if 0 <= y - 1 < cols:
queue.append((x, y - 1))
if 0 <= y + 1 < cols:
queue.append((x, y + 1))
queue.pop(0)
step += 1
rows, cols = len(matrix), len(matrix[0])
ans = matrix.copy()
for row in range(rows):
for col in range(cols):
if matrix[row][col] != 0:
bfs(ans, row, col)
return ans