← 返回 meta 的题目列表Shortest Path from the Leftmost Column to the Rightmost Column in a Blocked Grid
类型:online_judge
Given a binary rows × cols matrix grid:
0 represents a passable cell.
1 represents a blocked cell that cannot be visited.
You may start from any 0 cell in the leftmost column. Your goal is to reach any 0 cell in the rightmost column. In one step, move up, down, left, or right to an adjacent passable cell without leaving the grid.
Return the minimum number of cells in a valid path, including both the start and end cells. Return -1 if no path exists.
Input format
rows cols
grid[0][0] grid[0][1] ... grid[0][cols-1]
...
grid[rows-1][0] ... grid[rows-1][cols-1]
1 <= rows, cols <= 1000
grid[r][c] is either 0 or 1.
Example 1
Input
3 4
0 1 0 0
0 0 0 1
1 1 0 0
Output
5
One shortest path is (1,0) -> (1,1) -> (1,2) -> (2,2) -> (2,3).
Example 2
Input
2 3
1 0 1
1 0 1
Output
-1
Example
Input
3 4
0 1 0 0
0 0 0 1
1 1 0 0
Output
5