1. 程式人生 > >542. 01 Matrix(Two pass,動態規劃)

542. 01 Matrix(Two pass,動態規劃)

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:

  1. The number of elements of the given matrix will not exceed 10,000.
  2. There are at least one 0 in the given matrix.
  3. The cells are adjacent in only four directions: up, down, left and right.
class Solution:
    def updateMatrix(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[List[int]]
        """
        m,n = len(matrix),len(matrix[0])
        res = [[1000000 for i in range(n)] for j in range(m)]
        for i in range(m):  #First pass: check for left and top
            for j in range(n):
                if matrix[i][j]==0:
                    res[i][j] = 0
                else:
                    if i>0:
                        res[i][j] = min(res[i][j],res[i-1][j]+1)
                    if j>0:
                        res[i][j] = min(res[i][j],res[i][j-1]+1)
        for i in range(m-1,-1,-1): #Second pass: check for bottom and right
            for j in range(n-1,-1,-1):
                if i<m-1:
                    res[i][j] = min(res[i][j],res[i+1][j]+1)
                if j<n-1:
                    res[i][j] = min(res[i][j],res[i][j+1]+1)
        return res