题目
In an N by N square grid, each cell is either empty (0) or blocked (1).
A 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_iandC_{i+1}are connected 8-directionally (ie., they are different and share an edge or corner) C_1is at location(0, 0)(ie. has valuegrid[0][0])C_kis at location(N-1, N-1)(ie. has valuegrid[N-1][N-1])- If
C_iis located at(r, c), thengrid[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 <= grid.length == grid[0].length <= 100grid[r][c]is0or1
解析
典型的BFS算法, 用queue维护待搜索节点, 搜索过的节点要标注以避免死循环.
代码
c++
1 | class Solution { |