I just have tried to solve LeetCode's task 542. 01 Matrix. After a few attempts, I looked for a solution.
rows = len(matrix)
if rows == 0:
return []
cols = len(matrix[0])
dis = [[float('inf') for _ in range(cols)] for _ in range(rows)]
q = []
for i in range(rows):
for j in range(cols):
if matrix[i][j] == 0:
dis[i][j] = 0
q.append((i, j))
while len(q) > 0:
x, y = q.pop(0)
for (a, b) in ((x-1, y), (x+1, y), (x, y-1), (x, y+1)):
if 0 <= a < rows and 0 <= b < cols and dis[a][b] > dis[x][y] + 1:
dis[a][b] = dis[x][y] + 1
q.append((a, b))
return dis
To better understand the code, I changed the line
dis = [[float('inf') for _ in range(cols)] for _ in range(rows)]
to
dis = [[float('inf')]*cols]*rows
After the change, the code test failed. What is the difference between the two?