Python 3D Academyবাংলা

Choose, explore, undo: finding a way through a maze

🌍 In real life. At the village fair there is a hedge maze. You walk in and reach a fork. You choose a way and explore it. If it ends at a hedge, you don't give up: you walk back to the last fork and try the way you haven't tried yet. To avoid going round in circles you drop a pebble in every place you have been. Keep doing this and you either reach the exit or learn for sure that there is none.

This is backtracking: build an answer one choice at a time, and the moment a choice can't lead anywhere, undo it and try the next one. It solves puzzles where you must search through many possibilities, like mazes, Sudoku, seating plans and timetables, and this whole chapter uses it.

The idea in one sentence: backtracking builds an answer step by step: at each step it chooses one option, explores everything that follows from it, then undoes the choice so the next option starts from the same place.

Its words:

  • state: what has been chosen so far: here, the path walked and the cells already visited
  • choose: change the state by one choice (step into a cell)
  • explore: call the same function again, from the new state
  • undo: put the state back exactly as it was before the choice
  • dead end: a state with no choice left that can lead to an answer

Step by step, for the maze:

  1. if you are off the map, on a wall, or on a cell already visited, this way fails
  2. choose: mark the cell visited and add it to the path
  3. if it is the exit E, the path is the answer
  4. explore: try right, down, left and up, in that order; if any of them reaches E, so does this cell
  5. undo: none did, so take the cell off the path and report failure, and the caller tries its next direction

Watch: blue cells are the path so far, the gold one is the newest, and red ones are dead ends:

Why it is correct. Every cell you can reach from S is eventually tried from some neighbour, unless the exit is found first, because each cell tries all four directions before giving up. So if a way out exists, the search finds one. The undo is what keeps the path honest: when a cell is a dead end it is popped off, so the path always holds exactly the cells from S to where you stand now, with no detours left in it. The visited marks stop you from walking in circles: without them, two open cells next to each other would send you back and forth forever.

What it costs, by counting. In this search each cell is entered at most once (the visited mark is never removed), and each entered cell looks in 4 directions. So a maze of rows × cols cells costs at most about 4 × rows × cols looks: O(rows × cols). A 10 × 10 maze is at most about 400 looks.

When undo must also free the cell. To count every route from S to E, a cell used by one route must be free again for the next, so the undo also removes the visited mark. Then the work can grow very fast: an open 3 × 3 square already has 12 routes, and the number of routes grows exponentially with the size.

def find_path(maze):
    rows, cols = len(maze), len(maze[0])
    seen, path = set(), []
    def go(r, c):
        if not (0 <= r < rows and 0 <= c < cols):
            return False               # off the map
        if maze[r][c] == "#" or (r, c) in seen:
            return False               # a wall, or been here already
        seen.add((r, c))
        path.append((r, c))            # choose: step in
        if maze[r][c] == "E":
            return True
        for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
            if go(r + dr, c + dc):     # explore: right, down, left, up
                return True
        path.pop()                     # undo: a dead end
        return False
    for r, row in enumerate(maze):
        if "S" in row:
            go(r, row.index("S"))
    return path

print(find_path(["S...", "##.#", "...E"]))
print(find_path(["S#E", ".#."]))          # walled off: no way out

def count_ways(maze):
    rows, cols = len(maze), len(maze[0])
    seen = set()
    def go(r, c):
        if not (0 <= r < rows and 0 <= c < cols):
            return 0
        if maze[r][c] == "#" or (r, c) in seen:
            return 0
        if maze[r][c] == "E":
            return 1
        seen.add((r, c))               # choose
        ways = 0
        for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
            ways += go(r + dr, c + dc) # explore
        seen.discard((r, c))           # undo: free it for other routes
        return ways
    for r, row in enumerate(maze):
        if "S" in row:
            return go(r, row.index("S"))

print(count_ways(["S..", "...", "..E"]))

Mistakes and edge cases.

  • forgetting to undo: without path.pop() the dead ends stay in the path, and the answer is not a real route
  • no visited marks: the search walks back and forth between two cells until Python gives up with RecursionError: maximum recursion depth exceeded
  • checking the wall before the edge: maze[r][c] with r = -1 quietly reads the last row instead of failing, and r = rows raises IndexError; check the bounds first
  • counting routes but never freeing cells: the first route uses cells up, and later routes are missed
  • no S or no way out: the path comes back empty; check for that before using it

Quiz

  1. The ways to climb 3 stairs, 1 or 2 at a time. What does this print?

    path = []
    def go(n):
        if n == 0:
            print(path)
            return
        for step in (1, 2):
            if step <= n:
                path.append(step)
                go(n - step)
                path.pop()
    go(3)
  2. What is the job of the undo step?

    • Put the state back as it was before the choice, so the next choice starts from the same place
    • Stop the whole search
    • Make the search faster by skipping choices
  3. This should print [1, 1, 1], [1, 2] and [2, 1], but the lists keep growing. After which line is the undo missing?

    path = []
    def go(n):
        if n == 0:
            print(path)
            return
        for step in (1, 2):
            if step <= n:
                path.append(step)
                go(n - step)
    go(3)
  4. Why does the maze search mark every cell it enters?

    • So it never walks in circles: a cell already on the way is not entered again
    • To draw the maze
    • To find the shortest way
  5. Finding one way out, where each cell is entered at most once: how does the work grow for a rows × cols maze?

    • O(rows × cols): each cell once, 4 looks each
    • O(2^(rows × cols))
    • O(1)

Coding tasks

  1. Write find_path(maze): maze is a list of strings with one S, one E, walls # and open cells .. Search from S, trying right, down, left, up in that order, and return the path as a list of (row, col) tuples from S to E, or [] if there is no way out.

  2. Write count_ways(maze): how many different routes go from S to E, moving right, down, left or up, never visiting the same cell twice in one route. A cell used by one route must be free again for the next, so undo must free it.