# Leetcode: No.542 01 Matrix

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.
Example 1:
Input:

0 0 0
0 1 0
0 0 0
Output:
0 0 0
0 1 0
0 0 0
Example 2:
Input:

0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1
Note:
The number of elements of the given matrix will not exceed 10,000.
There are at least one 0 in the given matrix.
The cells are adjacent in only four directions: up, down, left and right.

0 0 0
0 1 0
0 0 0

0 0 0
0 1 0
0 0 0

0 0 0
0 1 0
1 1 1

0 0 0
0 1 0
1 2 1

### 思路描述：

##### 简而言之，由于BFS与距离的特性，初始化（1换成无限大）之后所有非0元素只需要一次有效计算就是正确的距离。

``````# Time:  O(m * n)
# Space: O(m * n)
import collections
import operator
class Solution(object):
def updateMatrix(self, matrix):
deque = collections.deque([])

for i in xrange(len(matrix)):
for j in xrange(len(matrix[0])):
if matrix[i][j] == 0:
deque.append((i, j))
else:
matrix[i][j] = float('inf')

directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
while deque:
e = deque.popleft()
for d in directions:
if not (0 <= k[0] < len(matrix)) or not (0 <= k[1] < len(matrix[0])) \
or (matrix[k[0]][k[1]] <= matrix[e[0]][e[1]] + 1):
continue
else:
matrix[k[0]][k[1]] = matrix[e[0]][e[1]] + 1
deque.append(k)

return matrix
``````

``````# Time:  O(m * n)
# Space: O(m * n)
# dp solution
class Solution2(object):
def updateMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
dp = [[float("inf")]*len(matrix[0]) for _ in xrange(len(matrix))]
for i in xrange(len(matrix)):
for j in xrange(len(matrix[i])):
if matrix[i][j] == 0:
dp[i][j] = 0
else:
if i > 0:
dp[i][j] = min(dp[i][j], dp[i-1][j]+1)
if j > 0:
dp[i][j] = min(dp[i][j], dp[i][j-1]+1)
for i in reversed(xrange(len(matrix))):
for j in reversed(xrange(len(matrix[i]))):
if matrix[i][j] == 0:
dp[i][j] = 0
else:
if i < len(matrix)-1:
dp[i][j] = min(dp[i][j], dp[i+1][j]+1)
if j < len(matrix[i])-1:
dp[i][j] = min(dp[i][j], dp[i][j+1]+1)
return dp
``````

``````def updateMatrix(self, matrix):
answer = [[10000 * x for x in row] for row in matrix]
for _ in range(4):
for j in range(1, len(row)):
row[j] = min(row[j], row[j-1] + 1)
`answer = [[10000 * x for x in row] for row in matrix]`这句代码是将矩阵进行初始化，不过因为`float('inf')*0=nan`即Not a number，这里选择10000来当乘数，因为根据题意距离总是会小于10000的。