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.
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:
neighbours(grid, tile): the tiles up, down, left and right oftile, in that order, that are inside the maze and not walls.shortest_path(grid, start, goal): the list of tiles fromstarttogoalin the fewest steps, found by breadth-first search;[start]if they're the same tile;Noneif there's no way through. If two ways tie, either will do.explore(grid, start): every tile a depth-first walk reaches fromstart, 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.unreachable(grid, start): every open tile (.,SorG) that can't be reached fromstart, row by row, left to right.draw_path(grid, path): the maze as a list of lines, with*on every tile of the path except theSand theG; the maze as it is ifpathisNone.
The main block solves the maze, draws the way, and reports how far depth first got and what's cut off.
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
- Places and the roads between
- One road away
- The circuit as a graph
- Nearest first
- Which comes out first?
- The way back
- Following the notes
- As far as it goes
- Every road to the end
- Tiles as places
- A maze is a graph
- How far Paul walks
- Fix Yahya's version
- Make the maze solver
- Ship it