【leetcode】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:

  • Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different and share an edge or corner)
  • C_1 is at location (0, 0) (ie. has value grid[0][0])
  • C_k is at location (N-1, N-1) (ie. has value grid[N-1][N-1])
  • If C_i is located at (r, c), then grid[r][c] is empty (ie. grid[r][c] == 0).

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[r][c] is 0 or 1

解題思路:典型的BFS問題。從起點開始依次計算每個方格到達的最小值即可。這里用visit[i][j]記錄從起點開始到(i,j)的最短路徑,在BFS的過程中,可能有多條路徑都能到達(i,j),因此只要有更短的走法能到達(i,j),就需要把(i,j)重新加入到隊列中。

代碼如下:

class Solution(object):
    def shortestPathBinaryMatrix(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        if grid[0][0] == 1:
            return -1
        visit = []
        val = []
        for i in grid:
            visit.append([0] * len(i))
            val.append([0] * len(i))
        visit[0][0] = 1
        queue = [(0,0)]
        direction = [(0,1),(0,-1),(1,0),(1,-1),(-1,1),(-1,-1),(1,1),(1,-1)]
        while len(queue) > 0:
            x,y = queue.pop(0)
            for (i,j) in direction:
                if x + i >= 0 and x+i < len(grid) and y + j >= 0 and y + j < len(grid[0]) \
                    and grid[x + i][y+j] == 0 and (visit[x+i][y+j] == 0 or visit[x+i][y+j] - 1 > visit[x][y]):
                    queue.append((x+i,y+j))
                    visit[x+i][y+j] = visit[x][y] + 1
        return visit[-1][-1] if visit[-1][-1] > 0 else -1

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM