GRPH-P7

Through the walls

Practice 7 of 7Graphs12 tests

The problem

A grid is given as a list of strings: '.' is an open square and '#' is a wall. Start on the top-left square and reach the bottom-right square. Each move goes one square up, down, left or right, and stays inside the grid. You may move onto at most k wall squares in total. Return the fewest moves, or -1 if the end cannot be reached.

grid = ['..#.',
        '#.#.',
        '..#.',
        '.##.']
fewest_moves(grid, 1)   # 6
fewest_moves(grid, 0)   # -1

The top-left and bottom-right squares are always open.

Limits

  • Up to 200 × 200 squares, and k up to 400.
  • Trying every route is far too slow. The two big tests with walls to break have 4 seconds each.

Builds on GRPH-7 Grids as graphs.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

12 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2No walls to breakNot run
3One squareNot run
4A row of wallsNot run
5Not enough breaksNot run
6One visit per square is not enoughNot run
7A wall saves many movesNot run
8Breaks to spareNot run
940 × 40Not run
10200 × 200, k = 0Not run
11200 × 200, k = 3Not run
12Walls everywhereNot run