Leetcode 1091. Shortest Path in Binary Matrix

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Shortest Path in Binary Matrix

2. Solution

**解析:**Version 1,如果起始点为1,直接返回-1,否则,使用广度优先搜索,使用grid[i][j]=1来表示访问过的点,从左上角开始,遍历满足条件的8个方向上的点,并将其坐标以及当前的长度保存到队列中,并将其值置为1,即已经访问过该点。第一次访问到右下角点时即为最短距离。

  • Version 1
class Solution:
    def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
        if grid[0][0] == 1:
            return -1
        n = len(grid)
        queue = collections.deque()
        queue.append((0, 0, 1))
        while queue:
            i, j, count = queue.popleft()
            if i == n - 1 and j == n - 1:
                return count
            count += 1
            if i > 0 and j > 0 and grid[i-1][j-1] == 0:
                grid[i-1][j-1] = 1
                queue.append((i-1, j-1, count))

            if i > 0 and grid[i-1][j] == 0:
                grid[i-1][j] = 1
                queue.append((i-1, j, count))

            if i > 0 and j < n-1 and grid[i-1][j+1] == 0:
                grid[i-1][j+1] = 1
                queue.append((i-1, j+1, count))

            if j > 0 and grid[i][j-1] == 0:
                grid[i][j-1] = 1
                queue.append((i, j-1, count))

            if j < n-1 and grid[i][j+1] == 0:
                grid[i][j+1] = 1
                queue.append((i, j+1, count))

            if i < n-1 and j > 0 and grid[i+1][j-1] == 0:
                grid[i+1][j-1] = 1
                queue.append((i+1, j-1, count))

            if i < n-1 and grid[i+1][j] == 0:
                grid[i+1][j] = 1
                queue.append((i+1, j, count))

            if i < n-1 and j < n-1 and grid[i+1][j+1] == 0:
                grid[i+1][j+1] = 1
                queue.append((i+1, j+1, count))

        return -1

Reference

  1. https://leetcode.com/problems/shortest-path-in-binary-matrix/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值