leetcode-542-01矩阵

Posted 真不知道叫啥好

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-542-01矩阵相关的知识,希望对你有一定的参考价值。

题目描述:

 

 方法一: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矩阵的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 542. 01 Matrix 01 矩阵(中等)

LeetCode——542. 01 矩阵

leetcode-542-01矩阵

[LeetCode] 542. 01 Matrix

[leetcode] 542. 01 Matrix (Medium)

LeetCode 542. 01 Matrix