Shortest path · Medium
A downloaded tile map marks blocked cells. Navigation needs the fewest orthogonal moves between two cells without contacting a routing service.
Return the shortest walk length or null when no walk exists.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ grid:number[][], start:[row,column], end:[row,column] }. grid is rectangular and nonempty; 0 is open and 1 is blocked
What each field means
grid— rectangular map;0is open and1is blocked.startandend— valid[row, column]positions.
Output
Return value and rules
- Return the fewest moves from start to end, moving up, down, left or right through open cells.
- Return
nullif either endpoint is blocked or no route exists. - An open start equal to end needs
0moves.
Constraints
- 1 <= rows, columns <= 200
- Only up, down, left and right moves are allowed; indexes are valid. Do not mutate grid.
Examples
Example 1
{
"end": [
1,
1
],
"grid": [
[
0,
0
],
[
1,
0
]
],
"start": [
0,
0
]
}Returns
2Example 2
{
"end": [
0,
0
],
"grid": [
[
0
]
],
"start": [
0,
0
]
}Returns
0Required complexity
O(rows × columns) time and space