其他分享
首页 > 其他分享> > 1091. Shortest Path in Binary Matrix

1091. Shortest Path in Binary Matrix

作者:互联网

In an N by N square grid, each cell is either empty (0) or blocked (1).

clear path from top-left to bottom-right has length k if and only if it is composed of cells C_1, C_2, ..., C_k such that:

Return the length of the shortest such clear path from top-left to bottom-right.  If such a path does not exist, return -1.

 

Example 1:

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

Example 2:

Input: [[0,0,0],[1,1,0],[1,1,0]]
Output: 4

 

Note:

  1. 1 <= grid.length == grid[0].length <= 100
  2. grid[i][j] is 0 or 1

思路:BFS

class Solution(object):
    def shortestPathBinaryMatrix(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        n,m=len(grid),len(grid[0])
        if grid[0][0]==1 or grid[n-1][m-1]==1: return -1
        vis=set([(n-1,m-1)])
        q,qq=[(n-1,m-1)],[]
        step=0
        dirs=[[1,0],[-1,0],[0,1],[0,-1],
              [1,1],[-1,1],[1,-1],[-1,-1]]
        while q:
            while q:
                i,j=q.pop()
                for di,dj in dirs:
                    ii,jj=i+di,j+dj
                    if 0<=ii<n and 0<=jj<m and grid[ii][jj]==0:
                        if (ii,jj) in vis: continue
                        vis.add((ii,jj))
                        qq.append((ii,jj))
                        if ii==0 and jj==0: return step+2
            step+=1
            q,qq=qq,q
        return -1
                    

 

标签:right,Matrix,int,grid,Path,such,path,ie,1091
来源: https://blog.csdn.net/zjucor/article/details/92384291