23/38
Part 5 of 7 · Graphs and backtrackingLearn

Backtracking: undo on the way out

Some questions ask about paths, not cells. Word search is the classic, and it's on Netflix's LeetCode company tag list (1 source). Given a grid of letters, is there a path of side-by-side cells that spells a word, using each cell at most once?

Here the seen-set is wrong in the opposite way. A cell belongs to the current path, not to the search forever. So a cell a failed path used must be free for the next path. Mark a cell on the way in and unmark it on the way out. That unmarking is the undo step, and a DFS with an undo step is backtracking.

Here's the shape on a smaller question: how many routes go from the top-left corner of an open grid to the bottom-right, moving between side-by-side cells and never visiting a cell twice?

def routes(grid):
    goal = (len(grid) - 1, len(grid[0]) - 1)
    on_path = {(0, 0)}

    def extend(cell):
        if cell == goal:
            return 1
        found = 0
        for nxt in open_neighbors(grid, *cell):
            if nxt not in on_path:
                # step in
                on_path.add(nxt)
                found += extend(nxt)
                # undo: step back out
                on_path.remove(nxt)
        return found

    return extend((0, 0))


print(routes(["..", ".."]), routes(["...", "...", "..."]))
Predict

How many routes go from the top-left to the bottom-right of an open 2 by 2 grid, never visiting a cell twice?

Pick one to see what it prints.
Pick an answer above to see the rest