1 """
2 Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
3 The distance between two adjacent cells is 1.
4 Example 1:
5 Input:
6 [[0,0,0],
7 [0,1,0],
8 [0,0,0]]
9 Output:
10 [[0,0,0],
11 [0,1,0],
12 [0,0,0]]
13 Example 2:
14 Input:
15 [[0,0,0],
16 [0,1,0],
17 [1,1,1]]
18 Output:
19 [[0,0,0],
20 [0,1,0],
21 [1,2,1]]
22 """
23 """
24 本题与leetcode1162题类似
25 先找出matrix中所有0的坐标,记录在队列q中,
26 并将值为1的地方赋为n+m,因为最远的距离也不会超过n+m
27 遍历q中元素q[i],更新q[i]周围四个点的距离,
28 更新了距离的点的坐标入队,直到遍历到q的最后一个元素为止
29 """
30 class Solution:
31 def updateMatrix(self, matrix):
32 queue = []
33 m = len(matrix) # m行
34 n = len(matrix[0]) # n列
35 for x in range(m):
36 for y in range(n):
37 if matrix[x][y] == 0: # 记录0所在的位置
38 queue.append((x, y))
39 else:
40 matrix[x][y] = m + n # 非0位置设为最大值
41 for x, y in queue: # 时间复杂度O(m*n*4)
42 for i, j in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]: #!!!上下左右四个方向遍历
43 if 0 <= i < m and 0 <= j < n and matrix[x][y] + 1 < matrix[i][j]: #注意边界0<=i<m
44 matrix[i][j] = matrix[x][y] + 1 #!!!记录距离
45 queue.append((i, j)) #将更改后距离的位置入队
46 return matrix