Python 3D Academyবাংলা

Searching words in a grid; counting prefixes

🌍 In real life. The newspaper's word search hides words in a grid of letters: you may go up, down, left or right from letter to letter, without using a square twice. With a list of 50 words to find, checking each word separately means 50 searches through the grid. A good solver does it once: from each square, they follow only letters that start some word on the list, and give up the moment no word could continue.

That is backtracking (Chapter 46) with a trie as its guide. The same trie, with a counter on every node, also answers "how many words start with...?" in a few steps.

The idea in one sentence: to find many words in a grid, put them all in a trie and backtrack from every square, moving to a neighbour only if its letter is a child of the current trie node; to count words by prefix, keep on every node the number of words that pass through it.

Its words:

  • grid search: a backtracking walk over neighbouring squares, each used at most once per word
  • pruning by prefix: stopping a walk as soon as the letters so far are not the start of any word
  • word at a node: storing the whole word where it ends, so the search knows what it found
  • pass count: on each node, how many inserted words go through it; that is exactly how many words start with its prefix

How the grid search works, step by step, from each square:

  1. if the square's letter is not a child of the current trie node, stop: no word on the list continues this way
  2. otherwise step down into that child; if a word ends there, record it
  3. mark the square used (choose), try its four neighbours (explore), then unmark it (undo)

The pass counts show in the trie: se has three words below it, te two, and set is not a word at all:

Why it is correct. The grid walk tries every path of neighbouring squares that spells the start of some word, because it only stops when the letters so far are no word's start, and then no longer path could help. Every word on such a path is recorded when its last letter is reached. The used-square mark keeps each word from using a square twice, and undoing it frees the square for other paths. Counting: a word passes through exactly the nodes of its prefixes, so the count on a node is the number of words that start with that node's prefix.

What it costs, by counting. Without the trie, each of w words is a separate grid search: w times the work. With it, one search covers all of them, and the pruning cuts most paths after a letter or two. In a 3 × 4 grid, after the first square a walk can branch in at most 3 directions (it never goes back to the square it came from). Most of those branches stop at once, because their letter is not a child of the current node. Counting prefixes costs O(L) per question after the trie is built, instead of checking every word each time.

class TrieNode:
    def __init__(self):
        self.children = {}
        self.word = None                 # the whole word, at the node where it ends

def find_words(grid, words):
    root = TrieNode()
    for w in words:
        node = root
        for ch in w:
            node = node.children.setdefault(ch, TrieNode())
        node.word = w
    found = set()
    board = [list(row) for row in grid]
    rows, cols = len(board), len(board[0])

    def go(r, c, node):
        ch = board[r][c]
        if ch not in node.children:
            return                       # no word goes this way: stop at once
        node = node.children[ch]
        if node.word is not None:
            found.add(node.word)
        board[r][c] = "#"                # choose: use this cell once
        for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols:
                go(nr, nc, node)         # explore
        board[r][c] = ch                 # undo

    for r in range(rows):
        for c in range(cols):
            go(r, c, root)
    return sorted(found)

grid = ["cats", "orea", "dogs"]
for row in grid:
    print(" ".join(row))
print(find_words(grid, ["cat", "cats", "care", "dog", "dogs", "rat", "code", "seat"]))

class CountNode:
    def __init__(self):
        self.children = {}
        self.count = 0                   # how many words pass through this node

def count_prefixes(words, queries):
    root = CountNode()
    for w in words:
        node = root
        for ch in w:
            node = node.children.setdefault(ch, CountNode())
            node.count += 1
    answers = []
    for q in queries:
        node = root
        for ch in q:
            node = node.children.get(ch)
            if node is None:
                break
        answers.append(0 if node is None else node.count)
    return answers

print(count_prefixes(["sea", "seat", "see", "tea", "ten"], ["se", "te", "sea", "x"]))

Mistakes and edge cases.

  • forgetting to undo the used mark: after the first word, its squares stay marked and later words that need them are missed
  • no used mark at all: a word could use the same square twice, like finding "aa" in a grid with a single a
  • a word found twice: two different paths can spell the same word; collect into a set (or clear node.word once found)
  • counting on the wrong node: add 1 to each node a word passes through, not just to the last one, or prefix counts only count exact words
  • a query that falls off the trie: node.children.get(ch) gives None; the count is 0

Quiz

  1. Which words are in this tiny grid?

    class TrieNode:
        def __init__(self):
            self.children = {}
            self.word = None                 # the whole word, at the node where it ends
    
    def find_words(grid, words):
        root = TrieNode()
        for w in words:
            node = root
            for ch in w:
                node = node.children.setdefault(ch, TrieNode())
            node.word = w
        found = set()
        board = [list(row) for row in grid]
        rows, cols = len(board), len(board[0])
    
        def go(r, c, node):
            ch = board[r][c]
            if ch not in node.children:
                return                       # no word goes this way: stop at once
            node = node.children[ch]
            if node.word is not None:
                found.add(node.word)
            board[r][c] = "#"                # choose: use this cell once
            for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                nr, nc = r + dr, c + dc
                if 0 <= nr < rows and 0 <= nc < cols:
                    go(nr, nc, node)         # explore
            board[r][c] = ch                 # undo
    
        for r in range(rows):
            for c in range(cols):
                go(r, c, root)
        return sorted(found)
    
    print(find_words(["ab", "cd"], ["abdc", "abcd", "acdb", "ba", "dd"]))
  2. What does this print?

    class CountNode:
        def __init__(self):
            self.children = {}
            self.count = 0                   # how many words pass through this node
    
    def count_prefixes(words, queries):
        root = CountNode()
        for w in words:
            node = root
            for ch in w:
                node = node.children.setdefault(ch, CountNode())
                node.count += 1
        answers = []
        for q in queries:
            node = root
            for ch in q:
                node = node.children.get(ch)
                if node is None:
                    break
            answers.append(0 if node is None else node.count)
        return answers
    
    print(count_prefixes(["sea", "seat", "see", "tea", "ten"], ["s", "sea", "t", "z"]))
  3. Why does the trie make the grid search faster than searching for each word separately?

    • One walk follows all the words at once, and stops as soon as no word continues
    • The trie sorts the grid
    • It only looks at the first row
  4. On the grid cats / orea / dogs this finds care, cat and cats, but misses dog, dogs and rat. After which line is a line missing?

    def go(r, c, node):
        ch = board[r][c]
        if ch not in node.children:
            return
        node = node.children[ch]
        if node.word is not None:
            found.add(node.word)
        board[r][c] = "#"
        for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols:
                go(nr, nc, node)

Coding tasks

  1. Write find_words(grid, words): grid is a list of equal-length strings; a word is found if its letters can be read by moving up, down, left or right from square to square, never using a square twice in one word. Return the found words, sorted, each once. Use a trie to stop early.

  2. Write count_prefixes(words, queries): for each query, how many of words start with it. Build one trie where every node counts the words passing through it, then answer each query by walking down.