leetcode - 542. 01 Matrix

Description

Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Example 1:

Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
Output: [[0,0,0],[0,1,0],[0,0,0]]

Example 2:

Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]

Constraints:

m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
mat[i][j] is either 0 or 1.
There is at least one 0 in mat.

Solution

BFS

Starts with all the positions with 0 as the value, and then use a dict to store the shortest distance. Update only when the new distance is shorter than existing ones.

Time complexity: o ( m ∗ n ) o(m*n) o(m∗n)

Space complexity: o ( m ∗ n ) o(m * n) o(m∗n)

DP

Use dp[i][j] to denote the distance for (i, j), then transformation equation is:
d p [ i ] [ j ] = m i n ( d p [ i − 1 ] [ j ] , d p [ i ] [ j − 1 ] , d p [ i ] [ j + 1 ] , d p [ i + 1 ] [ j ] ) + 1 dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i][j + 1], dp[i+1][j]) + 1 dp[i][j]=min(dp[i−1][j],dp[i][j−1],dp[i][j+1],dp[i+1][j])+1

So we could start with restricting the calculating only from left to right and up to down, that is we start with left-top corner, and then we start with right-bottom corner.

Time complexity: o ( m ∗ n ) o(m*n) o(m∗n)

Code

BFS

python3 复制代码
class Solution:
    def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
        import collections
        m, n = len(mat), len(mat[0])
        queue = collections.deque([(x, y, 0) for x in range(m) for y in range(n) if mat[x][y] == 0])
        res = {}
        while queue:
            x, y, v = queue.popleft()
            if res.get((x, y), m + n) < v:
                continue
            res[(x, y)] = v
            for dx in (1, -1):
                if 0 <= x + dx < m and mat[x + dx][y] == 1:
                    queue.append((x + dx, y, v + 1))
                if 0 <= y + dx < n and mat[x][y + dx]:
                    queue.append((x, y + dx, 1 + v))
        ret_mat = [[0] * n for _ in range(m)]
        for x in range(m):
            for y in range(n):
                ret_mat[x][y] = res[(x, y)]
        return ret_mat

DP

python3 复制代码
class Solution:
    def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
        m, n = len(mat), len(mat[0])
        dp = [[0] * n for _ in range(m)]
        for i in range(m):
            for j in range(n):
                if i == 0 and j == 0:
                    dp[i][j] = 0 if mat[i][j] == 0 else m + n
                elif i == 0:
                    dp[i][j] = dp[i][j - 1] + 1 if mat[i][j] == 1 else 0
                elif j == 0:
                    dp[i][j] = dp[i - 1][j] + 1 if mat[i][j] == 1 else 0
                else:
                    dp[i][j] = 0 if mat[i][j] == 0 else min(dp[i - 1][j], dp[i][j - 1]) + 1
        for i in range(m - 1, -1, -1):
            for j in range(n - 1, -1, -1):
                if i == m - 1 and j == n - 1:
                    dp[i][j] = 0 if mat[i][j] == 0 else dp[i][j]
                elif i == m - 1:
                    dp[i][j] = min(dp[i][j], dp[i][j + 1] + 1)
                elif j == n - 1:
                    dp[i][j] = min(dp[i][j], dp[i + 1][j] + 1)
                else:
                    dp[i][j] = 0 if mat[i][j] == 0 else min(dp[i][j], min(dp[i + 1][j], dp[i][j + 1]) + 1)
        return dp
相关推荐
sp_fyf_202414 分钟前
计算机前沿技术-人工智能算法-大语言模型-最新研究进展-2024-10-02
人工智能·神经网络·算法·计算机视觉·语言模型·自然语言处理·数据挖掘
我是哈哈hh2 小时前
专题十_穷举vs暴搜vs深搜vs回溯vs剪枝_二叉树的深度优先搜索_算法专题详细总结
服务器·数据结构·c++·算法·机器学习·深度优先·剪枝
Tisfy2 小时前
LeetCode 2187.完成旅途的最少时间:二分查找
算法·leetcode·二分查找·题解·二分
Mephisto.java2 小时前
【力扣 | SQL题 | 每日四题】力扣2082, 2084, 2072, 2112, 180
sql·算法·leetcode
robin_suli2 小时前
滑动窗口->dd爱框框
算法
丶Darling.2 小时前
LeetCode Hot100 | Day1 | 二叉树:二叉树的直径
数据结构·c++·学习·算法·leetcode·二叉树
labuladuo5202 小时前
Codeforces Round 977 (Div. 2) C2 Adjust The Presentation (Hard Version)(思维,set)
数据结构·c++·算法
jiyisuifeng19913 小时前
代码随想录训练营第54天|单调栈+双指针
数据结构·算法
꧁༺❀氯ྀൢ躅ྀൢ❀༻꧂3 小时前
实验4 循环结构
c语言·算法·基础题
新晓·故知3 小时前
<基于递归实现线索二叉树的构造及遍历算法探讨>
数据结构·经验分享·笔记·算法·链表