Paul's Python CoursePPC

Project 11 of 15, for Neil

Maze Solver

A maze solver for Neil's race weekend: graphs first, on the roads round the circuit, then the car park as a grid, solved breadth first for the fewest steps to his car and depth first for everywhere that can be reached.

About an hour and a half, in 16 steps.

Sign up free to open itLog in

Act 4 needs a free account, so your work is saved as you go. Act 1 is open to everyone.

The brief

  • NeilIt's race weekend, and the circuit's car park is a field of hedges with one gate and my car in it.
  • NeilThe steward says it's twenty-three steps from the gate to my car, but I reckon nineteen's possible.
  • NeilI also want to know if any space is hedged in so nobody can get to it.
  • PaulIf you write it down as places and the ways between them, what you've got is a graph.

maze.txt is the car park, drawn as text: # is a hedge, a wall to you, . is open grass, S is the gate and G is Neil's car. A tile is a (row, col) pair. read_maze is written: it gives back (grid, start, goal), where grid is the list of lines. In maze.py, write:

  1. neighbours(grid, tile): the tiles up, down, left and right of tile, in that order, that are inside the maze and not walls.
  2. shortest_path(grid, start, goal): the list of tiles from start to goal in the fewest steps, found by breadth-first search; [start] if they're the same tile; None if there's no way through. If two ways tie, either will do.
  3. explore(grid, start): every tile a depth-first walk reaches from start, in the order it first reaches them. From each tile, try its neighbours in order; go to the first one not reached yet and carry on from there; when a tile has nowhere new, go back the way you came and try the next.
  4. unreachable(grid, start): every open tile (., S or G) that can't be reached from start, row by row, left to right.
  5. draw_path(grid, path): the maze as a list of lines, with * on every tile of the path except the S and the G; the maze as it is if path is None.

The main block solves the maze, draws the way, and reports how far depth first got and what's cut off.

What it prints
Start to goal: 19 steps
S.....#.......#.....
*####.#.......#.###.
*#....#..###....#...
*#.####..#G..####.#.
*#.......#*#......#.
*######..#*#.####.#.
***********.....#.#.
.####.#######.#.#...
......#.#...#.#...#.
Depth first reaches 111 tiles
Cut off: (8, 7), (8, 9), (8, 10), (8, 11)

What you learn

What's in it

  1. Places and the roads between
  2. One road away
  3. The circuit as a graph
  4. Nearest first
  5. Which comes out first?
  6. The way back
  7. Following the notes
  8. As far as it goes
  9. Every road to the end
  10. Tiles as places
  11. A maze is a graph
  12. How far Paul walks
  13. Fix Yahya's version
  14. Make the maze solver
  15. Ship it