首页 > 其他 > 详细

leetcode-542-01矩阵

时间:2020-04-16 00:56:46      阅读:64      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

 

 方法一:dfs O(MN) O(MN)

class Solution:
    def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
        m,n = len(matrix),len(matrix[0])
        dist = [[0] * n for _ in range(m)]
        zeroes_pos = [(i,j) for i in range(m) for j in range(n) if matrix[i][j] == 0]
        q = collections.deque(zeroes_pos)
        seen = set(zeroes_pos)
        while q:
            i,j = q.popleft()
            for ni,nj in [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]:
                if 0 <= ni <m and 0 <= nj <n and (ni,nj) not in seen:
                    dist[ni][nj] = dist[i][j] + 1
                    q.append((ni,nj))
                    seen.add((ni,nj))
        return dist

方法二:动态规划 O(MN)O(1)

class Solution:
    def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
        m,n = len(matrix),len(matrix[0])
        dist = [[10**9] * n for _ in range(m)]
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == 0:
                    dist[i][j] = 0
        for i in range(m):
            for j in range(n):
                if i - 1 >= 0:
                    dist[i][j] = min(dist[i][j],dist[i-1][j]+1)
                if j - 1 >= 0:
                    dist[i][j] = min(dist[i][j],dist[i][j-1]+1)
        for i in range(m -1,-1,-1):
            for j in range(n - 1, -1,-1):
                if i+1<m:
                    dist[i][j] = min(dist[i][j],dist[i+1][j]+1)
                if j+1 < n:
                    dist[i][j] = min(dist[i][j],dist[i][j+1] +1)
        return dist

 

leetcode-542-01矩阵

原文:https://www.cnblogs.com/oldby/p/12709615.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!