Python coding

Words hidden in a grid

Given a letter grid board (a list of equal-length strings) and a list words, return every word that can be traced in the grid, each once, sorted alphabetically. To trace a word, start on any cell and move up, down, left or right to the next letter; a cell can be used at most once within the same word.

Letters are lowercase a–z; the grid has 1 to 12 rows and columns, and words may contain repeats.

  • find_words(["cat","ore","dog"], ["cat","car","rate","ore","rod","ego","tea","cord"]) → ["car","cat","ego","ore","rate","rod"]
  • find_words(["ab","cd"], ["aba","abdc","ad","acdb"]) → ["abdc","acdb"]
  • find_words(["star"], ["st","sta","star","stars","rats"]) → ["rats","st","sta","star"]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Searching each word on its own repeats the grid DFS once per word. Put all the words in one trie and run a single DFS from every cell.

Hint 2

Step down the trie as you step across the grid, and stop as soon as the cell's letter has no child. Mark the cell before recursing and restore it after.

Hint 3

Store the whole word at its end node; when you reach it, record it and remove the marker so it is reported once, then keep exploring.

Solution and why it works
pythonO(R·C·4·3^(L−1)), R×C grid, L = longest word · O(W + L), W = total characters in words
def find_words(board: list[str], words: list[str]) -> list[str]:
    root = {}
    for w in words:
        node = root
        for ch in w:
            node = node.setdefault(ch, {})
        node["$"] = w
    grid = [list(row) for row in board]
    found = []

    def dfs(r: int, c: int, parent: dict) -> None:
        if not (0 <= r < len(grid) and 0 <= c < len(grid[0])) or grid[r][c] not in parent:
            return
        ch = grid[r][c]
        node = parent[ch]
        if "$" in node:
            found.append(node.pop("$"))
        grid[r][c] = "#"
        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            dfs(r + dr, c + dc, node)
        grid[r][c] = ch

    for r in range(len(grid)):
        for c in range(len(grid[0])):
            dfs(r, c, root)
    return sorted(found)

One trie lets a single DFS per cell search for every word at once: step down the trie as you step across the grid, and abandon a path the moment it is nobody's prefix. Mark the cell before recursing and restore it after, or later paths lose letters. The trap is stopping at the first match: "st" ends where "star" continues, so record the word, pop its marker so it is reported once, and keep going.