22/35
Part 6 of 7 · The worked exampleLearn

Put every word in one trie, and carry its node along one search from each cell

3. The insight. Put all the words in one trie, and run one depth-first search from each cell, carrying the trie node for the path so far. A step into a neighbor happens only if the trie has a child for that cell's letter. A path that no word continues dies at once, and a path that a thousand words share is walked once.

SIDES = ((-1, 0), (1, 0), (0, -1), (0, 1))


def words_on_grid(grid, words):
    trie = {}
    for word in words:
        node = trie
        for ch in word:
            node = node.setdefault(ch, {})
        # the marker holds the word, so a find builds no string
        node[END] = word
    rows, cols = len(grid), len(grid[0])
    found, used = [], set()

    def visit(r, c, parent):
        node = parent.get(grid[r][c])
        if node is None:
            # no word goes on with this letter
            return
        if END in node:
            # report it once, then forget it
            found.append(node.pop(END))
        used.add((r, c))
        for dr, dc in SIDES:
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and (nr, nc) not in used:
                visit(nr, nc, node)
        # the undo step
        used.remove((r, c))
        if not node:
            # nothing left to find below: cut the branch
            del parent[grid[r][c]]

    for r in range(rows):
        for c in range(cols):
            visit(r, c, trie)
    return sorted(found)


GRID = ["tarp", "ento", "aesl"]
WORDS = ["tent", "tents", "tea", "tarp", "stop", "pots", "top", "sea", "lamp", "seal"]
print(words_on_grid(GRID, WORDS))
Predict

The grid's rows are tarp, ento and aesl. Which of these words does it not spell: tea, stop or seal?

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