Algo-Sim › Tries

Word Search II

Hard · Tries · step through it in Java, Python and C++ on your own input

Put every word in one trie, then DFS the board once from each cell, walking the trie alongside and stopping as soon as the path is not a prefix.

Problem

Given an m × n board of letters and a list of distinct words, return every word that can be spelled on the board. A word is spelled by a path of cells, each next to the previous one horizontally or vertically, and a cell can be used at most once in a word. The answer can be in any order.

Constraints

Edge cases to test

Follow-up questions

Why prune found words from the trie?
Removing a word’s end mark (and empty branches) stops later searches from walking dead paths: a big speedup in practice.
Why a trie instead of one search per word?
All words are searched in one DFS from each cell, sharing their common prefixes.

Solution

Java

private static class Node {
    Node[] next = new Node[26];
    String word;                     // set on the node where a word ends
}

public List<String> findWords(char[][] board, String[] words) {
    Node root = new Node();
    for (String w : words) {
        Node node = root;
        for (char ch : w.toCharArray()) {
            if (node.next[ch - 'a'] == null) node.next[ch - 'a'] = new Node();
            node = node.next[ch - 'a'];
        }
        node.word = w;
    }
    List<String> found = new ArrayList<>();
    for (int r = 0; r < board.length; r++) {
        for (int c = 0; c < board[0].length; c++) {
            dfs(board, r, c, root, found);
        }
    }
    return found;
}

private void dfs(char[][] board, int r, int c, Node parent, List<String> found) {
    char ch = board[r][c];
    Node node = parent.next[ch - 'a'];
    if (node == null) return;
    if (node.word != null) {
        found.add(node.word);
        node.word = null;
    }
    board[r][c] = '#';
    int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    for (int[] d : dirs) {
        int nr = r + d[0], nc = c + d[1];
        if (nr < 0 || nc < 0 || nr >= board.length || nc >= board[0].length) continue;
        if (board[nr][nc] == '#') continue;
        dfs(board, nr, nc, node, found);
    }
    board[r][c] = ch;
}

Python

class Node:
    def __init__(self):
        self.next = [None] * 26
        self.word = None                     # set on the node where a word ends


def find_words(board, words):
    root = Node()
    for w in words:
        node = root
        for ch in w:
            i = ord(ch) - ord("a")
            if node.next[i] is None:
                node.next[i] = Node()
            node = node.next[i]
        node.word = w
    rows, cols = len(board), len(board[0])
    found = []

    def dfs(r, c, parent):
        ch = board[r][c]
        node = parent.next[ord(ch) - ord("a")]
        if node is None:
            return
        if node.word is not None:
            found.append(node.word)
            node.word = None
        board[r][c] = "#"
        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] != "#":
                dfs(nr, nc, node)
        board[r][c] = ch

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

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    class Node {
      public:
        vector<Node *> next = vector<Node *>(26, nullptr);
        string word; // set on the node where a word ends
    };

    vector<string> findWords(vector<vector<char>> &board, vector<string> &words) {
        Node *root = new Node();
        for (string w : words) {
            Node *node = root;
            for (char ch : w) {
                if (node->next[ch - 'a'] == nullptr)
                    node->next[ch - 'a'] = new Node();
                node = node->next[ch - 'a'];
            }
            node->word = w;
        }
        vector<string> found = {};
        for (int r = 0; r < int(board.size()); r++) {
            for (int c = 0; c < int(board[0].size()); c++) {
                dfs(board, r, c, root, found);
            }
        }
        return found;
    }

    void dfs(vector<vector<char>> &board, int r, int c, Node *parent, vector<string> &found) {
        char ch = board[r][c];
        Node *node = parent->next[ch - 'a'];
        if (node == nullptr)
            return;
        if (!node->word.empty()) {
            found.push_back(node->word);
            node->word.clear();
        }
        board[r][c] = '#';
        vector<vector<int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        for (vector<int> &d : dirs) {
            int nr = r + d[0], nc = c + d[1];
            if (nr < 0 || nc < 0 || nr >= int(board.size()) || nc >= int(board[0].size()))
                continue;
            if (board[nr][nc] == '#')
                continue;
            dfs(board, nr, nc, node, found);
        }
        board[r][c] = ch;
    }
};

More Tries problems