Breadth first search · Hard
An offline map permits crossing up to k blocked cells using a limited repair allowance. The fastest route may require preserving allowance for later.
Find the fewest moves from the top-left to bottom-right cell with at most k obstacle entries.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ grid:number[][], budget:integer }. 0 is open, 1 is blocked; start and end are guaranteed open
What each field means
grid— rectangular map;0is open and1is blocked.budget— maximum number of entries into blocked cells.- Start is the top-left cell and destination is the bottom-right cell; both are open.
Output
Return value and rules
- Return the fewest orthogonal moves that reach the destination without exceeding the budget.
- Every entry into a blocked cell costs one allowance, including revisits.
- Return
nullwhen no permitted route exists. A one-cell map needs0moves.
Constraints
- 1 <= rows, columns <= 40; 0 <= budget <= 20
- Orthogonal moves only; do not mutate grid.
Examples
Example 1
{
"budget": 1,
"grid": [
[
0,
1,
0
],
[
0,
1,
0
],
[
0,
0,
0
]
]
}Returns
4Example 2
{
"budget": 0,
"grid": [
[
0
]
]
}Returns
0Required complexity
O(rows × columns × (budget+1)) time and space