Breadth first search · Medium
A map viewer needs the shortest route across a small rectangular warehouse plan. Moving one cell costs one step; blocked cells cannot be entered. Unlike the route-counting exercise, movement can go up, down, left or right.
Return the minimum number of moves from the top-left to the bottom-right clear cell or -1 if no route exists.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "grid": number[][] } containing only 0 and 1.
Fields
- grid is a rectangular array containing only 0 (clear) and 1 (blocked).
Output
Return value
- Return a move count, not the number of visited cells.
- An empty dimension, blocked endpoint or disconnected destination returns -1.
- A single clear cell returns 0. Diagonal moves are forbidden.
Constraints
- 0 <= rows, columns <= 500.
Examples
Example 1
{
"grid": [
[
0,
1
],
[
0,
0
]
]
}Returns
2Down then right.
Example 2
{
"grid": [
[
0,
1
],
[
1,
0
]
]
}Returns
-1The diagonal does not connect the endpoints.
Required complexity
O(rows * columns) time and space