667. Walls You Can Break

A courier crosses a city block map grid from the top-left cell to the bottom-right cell, moving one step up, down, left or right each time. A cell holding 0 is an open street and a cell holding 1 is a barricade. The courier carries a permit that allows dismantling at most k barricades during the whole trip: stepping onto a barricade cell uses up one of the k allowances, after which that cell is simply passable.

Return the smallest number of steps needed to reach the bottom-right cell, or -1 if it cannot be done within the allowance. A map with a single cell needs 0 steps. The allowance may be far larger than the map, and the map can have tens of thousands of cells, so your search must not blow up with the value of k.

Example 1

Input:
grid = [[0,1,1],[1,1,0],[0,1,0]], k = 2
Output:
4
Explanation:

Go right along the top row and then down: the cells (0,1) and (0,2) are barricades, which uses both allowances, and the path has 4 steps.

Example 2

Input:
grid = [[0,1,1],[1,1,0],[0,1,0]], k = 1
Output:
-1
Explanation:

Every route from the start to the goal crosses at least two barricades, so one allowance is not enough and the answer is -1.

Example 3

Input:
grid = [[0,0,0],[0,0,0]], k = 0
Output:
3
Explanation:

The map is fully open, so the shortest route is 3 steps with no barricade removed.

Constraints

1 ≤ rows, cols ≤ 200

each cell is 0 or 1; the starting cell is never charged

0 ≤ k ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms

Expected complexity

Time
O(rows*cols*min(k, rows+cols))
Space
O(rows*cols)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…