# python BFS solution

• Here used some tricks learned from @StefanPochmann

``````class Solution(object):
def updateMatrix(self, matrix):
q, m, n = [], len(matrix), len(matrix[0])
for i in xrange(m):
for j in xrange(n):
if matrix[i][j] != 0:
matrix[i][j] = 0x7fffffff
else:
q.append((i, j))
for i, j in q:
for r, c in ((i, 1+j), (i, j-1), (i+1, j), (i-1, j)):
z = matrix[i][j] + 1
if 0 <= r < m and 0 <= c < n and matrix[r][c] > z:
matrix[r][c] = z
q.append((r, c))
return matrix``````

• I've never seen `r not in (-1, m)`, I think `0 <= r < m` is much better.

• @StefanPochmann Yeah, I was doing something like this, but forgot to rewrite the code. Thanks for the reminder.

``````if r in (-1, m) or c in (-1, n):
continue
``````

• what is going on here?

for i, j in q:
for r, c in ((i, 1+j), (i, j-1), (i+1, j), (i-1, j)):
z = matrix[i][j] + 1
if 0 <= r < m and 0 <= c < n and matrix[r][c] > z:
matrix[r][c] = z
q.append((r, c))
return matrix

especially here:
matrix[r][c] > z

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.