sagelearnai

Word Search II

Difficulty: Hard · Pattern: Tries · LeetCode #212

Given a letter grid board and a list of words, return every word that can be formed from a path of horizontally/vertically adjacent cells, using each cell at most once per word. Return the found words in any order.

Example

text
board = [["o","a","a","n"],
         ["e","t","a","e"],
         ["i","h","k","r"],
         ["i","f","l","v"]]
words = ["oath", "pea", "eat", "rain"]   →  ["eat", "oath"]

Hints

  1. Running Word Search separately for every word repeats a lot of work.
  2. Put all words in a trie. DFS from each cell, following trie edges, so you search for all words simultaneously.
  3. Stop exploring as soon as the current path is not a prefix of any word.

Approach

Build a trie of the words, storing the complete word at its end node. DFS from every cell: move into a child only if the board letter exists among the current trie node's children (prefix pruning). When you reach a node holding a word, record it and clear it (to avoid duplicates). Mark cells as visited during the path and restore them afterwards. An optional optimization prunes trie leaves once their words are found, which shrinks later searches.

Complexity

Time: O(R·C·4·3^(L−1)) worst case for max word length L; prefix pruning makes it much faster in practice. Space: O(total letters in words).

Python solution
def findWords(board, words):
    root = {}
    for w in words:
        node = root
        for ch in w:
            node = node.setdefault(ch, {})
        node["$"] = w
    R, C, found = len(board), len(board[0]), []
    def dfs(r, c, parent):
        ch = board[r][c]
        node = parent[ch]
        if "$" in node:
            found.append(node.pop("$"))
        board[r][c] = "#"
        for nr, nc in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
            if 0 <= nr < R and 0 <= nc < C and board[nr][nc] in node:
                dfs(nr, nc, node)
        board[r][c] = ch
        if not node:                     # prune exhausted branches
            parent.pop(ch)
    for r in range(R):
        for c in range(C):
            if board[r][c] in root:
                dfs(r, c, root)
    return found
JavaScript solution
function findWords(board, words) {
  const root = {};
  for (const w of words) { let node = root; for (const ch of w) node = node[ch] || (node[ch] = {}); node.$ = w; }
  const R = board.length, C = board[0].length, found = [];
  const dfs = (r, c, parent) => {
    const ch = board[r][c], node = parent[ch];
    if (node.$) { found.push(node.$); delete node.$; }
    board[r][c] = '#';
    for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
      if (nr >= 0 && nc >= 0 && nr < R && nc < C && node[board[nr][nc]]) dfs(nr, nc, node);
    }
    board[r][c] = ch;
    if (Object.keys(node).length === 0) delete parent[ch];
  };
  for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) if (root[board[r][c]]) dfs(r, c, root);
  return found;
}