Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Shortest path with walls you may break

Hard · Target 30 minutes · Graphs · Type asked atGoogleAmazon

A grid holds 0 for an open cell and 1 for a wall. You start at the top-left cell and want to reach the bottom-right cell, moving up, down, left or right one cell per step. You may walk through at most k walls in total. Return the fewest steps needed, or −1 if it cannot be done. Both corners are open.

Examples

InputOutputWhy
grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 16Break the wall at (3, 2): the path drops straight down the right side.
grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1-1Every route crosses at least two walls.
grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]], k = 010No walls may be broken: the path winds around both.

Constraints

  • 1 ≤ rows, cols ≤ 40
  • 0 ≤ k ≤ rows · cols
  • grid[0][0] = grid[rows − 1][cols − 1] = 0

Hints

Hint 1

Plain breadth-first search over cells fails: reaching a cell with more walls still allowed is better, even if it took longer.

Hint 2

Make the state (row, col, walls left). Two visits to the same cell with different walls left are different states.

Hint 3

Breadth-first search over those states; the first time any state at the target is reached, its distance is the answer.

Where people lose marks

  • Marking cells, not states, as visited: an early arrival with no walls left blocks a later, more useful one.
  • Spending a wall on the target or the start, which are open.
  • Forgetting the shortcut when k is large, so the state space becomes huge for no reason.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.