这道题目不难,主要用到的思想是BFS。重要的是理清思路。 a.首先从0开始,搜索周围的未被check过的1,把这些1全部赋值为1,并设置状态为checked,把这些1进行保存。 b.从上面保存的1开始搜索周围的未被check过的1,把这些1全部赋值为2,并设置状态为checked,把这些2进行保存。 c.从上面保存的2开始搜索周围的未被check过的1,把这些1全部赋值为3,并设置状态为checked,把这些3进行保存。 .... d.直到保存的点是empty,程序退出。
class Solution(object):
def updateMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
start_points = []
row = len(matrix)
col = len(matrix[0])
if_check = [[False] * col for i in range(row)]
for i in range(row):
for j in range(col):
if matrix[i][j] == 0:
start_points.append((i, j))
if_check[i][j] = True
depth = 1
while len(start_points) != 0:
new_start_points = []
for start_point in start_points:
row_idx, col_idx = start_point
if row_idx >= 1 and if_check[row_idx-1][col_idx] == 0:
matrix[row_idx-1][col_idx] = depth
if_check[row_idx-1][col_idx] = True
new_start_points.append((row_idx-1, col_idx))
if col_idx >= 1 and if_check[row_idx][col_idx-1] == 0:
matrix[row_idx][col_idx-1] = depth
if_check[row_idx][col_idx-1] = True
new_start_points.append((row_idx, col_idx-1))
if col_idx < col-1 and if_check[row_idx][col_idx+1] == 0:
matrix[row_idx][col_idx+1] = depth
if_check[row_idx][col_idx+1] = True
new_start_points.append((row_idx, col_idx+1))
if row_idx < row-1 and if_check[row_idx+1][col_idx] == 0:
matrix[row_idx+1][col_idx] = depth
if_check[row_idx+1][col_idx] = True
new_start_points.append((row_idx+1, col_idx))
depth += 1
start_points = new_start_points
return matrix
if __name__ == "__main__":
S = Solution()
matrix = []
matrix.append([0, 0, 0])
matrix.append([0, 1, 0])
#matrix.append([0, 0, 0])
matrix.append([1, 1, 1])
S.updateMatrix(matrix)
print(matrix)