码迷,mamicode.com
首页 > 其他好文 > 详细

542. 01 Matrix(Two pass,动态规划)

时间:2018-12-01 21:50:58      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:and   one   ott   dir   动态   input   cond   tput   lse   

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

542. 01 Matrix(Two pass,动态规划)

标签:and   one   ott   dir   动态   input   cond   tput   lse   

原文地址:https://www.cnblogs.com/bernieloveslife/p/10050664.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!