← 返回 snowflake 的题目列表Shortest Path in a Binary Matrix with Obstacles
类型:online_judge
Problem: Shortest Path in a Binary Matrix with Obstacles
You are given an m x n binary matrix grid, where:
0 means the cell is passable;
1 means the cell is blocked and cannot be used.
You are also given a start cell (sr, sc) and a target cell (tr, tc). Return the minimum number of steps needed to move from the start cell to the target cell.
In one step, you may move to one of the four neighboring cells: up, down, left, or right. You cannot move outside the matrix or into a blocked cell.
If the target cannot be reached, return -1.
Input Format
m n
grid[0][0] grid[0][1] ... grid[0][n-1]
...
grid[m-1][0] ... grid[m-1][n-1]
sr sc tr tc
Output Format
minimum distance
Constraints
1 <= m, n <= 1000
grid[i][j] is either 0 or 1
0 <= sr, tr < m
0 <= sc, tc < n
Example
Input:
3 4
0 0 0 1
1 1 0 1
0 0 0 0
0 0 2 3
Output:
5
Explanation: One shortest path from (0,0) to (2,3) has length 5.
Example
Input
3 4
0 0 0 1
1 1 0 1
0 0 0 0
0 0 2 3
Output
5