Python 小白的 Leetcode Daily Challenge 刷题计划 - 20230817

542. 01 Matrix

难度:Medium

  • 直接以所有 0 位置为起点进行 BFS 遍历即可
  • 为了减小空间常数,使用 cur, nxt 两个 list,而不是一开始开一个长为元素个数 m×n 的 list 来模拟队列
  • 时间复杂度O(m\times n)

class Solution:
    def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
        m = len(mat)
        n = len(mat[0])
        dis = []
        for i in range(m):
            dis.append([-1] * n)
        head = 0
        tail = 0
        cur = []
        nxt = []
        for i in range(m):
            for j in range(n):
                if mat[i][j] == 0:
                    dis[i][j] = 0
                    cur.append((i, j))
        dx = [-1, 1, 0, 0]
        dy = [0, 0, -1, 1]
        while cur:
            nxt.clear()
            for x, y in cur:
                for i in range(4):
                    nx = x + dx[i]
                    ny = y + dy[i]
                    if nx < 0 or nx >= m or ny < 0 or ny >= n or dis[nx][ny] != -1:
                        continue
                    dis[nx][ny] = dis[x][y] + 1
                    nxt.append((nx, ny))
            cur.clear()
            for coord in nxt:
                cur.append(coord)
        return dis

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值