Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Trie

Word Search II

Hard · Trie · Asked at Amazon, Microsoft, Google, Uber, Airbnb

Find every word from the list that can be traced in the letter grid by moving up, down, left or right between adjacent cells, without using a cell twice in the same word. Print the found words in lexicographic order, one per line, or NONE.

Input

First line: R C. Next R lines: a string of C lowercase letters. Then a line with n, and n lines with one word each (all distinct).

Output

The found words in lexicographic order, or NONE.

Constraints

Searching each word separately repeats work. Insert all words into a trie and run one DFS from every cell that walks the grid and the trie together, stopping as soon as the path is not a prefix of any word. Mark found words so each is reported once.

Example 1

Input

4 4
oaan
etae
ihkr
iflv
4
oath
pea
eat
rain

Output

eat
oath

Example 2

Input

2 2
ab
cd
1
abcb

Output

NONE

Hints

  1. Searching for each word separately repeats the same grid walks.
  2. Put all words in a trie: a walk on the grid is useful only while its letters form a prefix in the trie.
  3. Mark the trie node of a found word so it is reported once.

Approach

Insert every word into a trie, storing the word at its last node. Start a DFS from every cell with the trie root. Step into a cell only if the trie has a child for its letter; if that child ends a word, record it. Mark the cell as used during the DFS and unmark it on the way back. Sort the found words and print them, or NONE. Pruning by the trie keeps the search small even with thousands of words.

Complexity: O(R · C · 4 · 3^(L−1)) worst case, much less in practice · O(total letters) trie space

Solution

C++ solution

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

struct Trie {
    int next[26];
    int word = -1;
    Trie() { memset(next, -1, sizeof next); }
};

int R, C;
vector<string> g, words;
vector<Trie> t(1);
vector<vector<bool>> used;
set<string> found;

void dfs(int x, int y, int node) {
    int nx = t[node].next[g[x][y] - 'a'];
    if (nx == -1) return;
    if (t[nx].word >= 0) found.insert(words[t[nx].word]);
    used[x][y] = true;
    int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
    for (int d = 0; d < 4; d++) {
        int a = x + dx[d], b = y + dy[d];
        if (a >= 0 && b >= 0 && a < R && b < C && !used[a][b]) dfs(a, b, nx);
    }
    used[x][y] = false;
}

int main() {
    cin >> R >> C;
    g.resize(R);
    for (auto &row : g) cin >> row;
    int n;
    cin >> n;
    words.resize(n);
    for (int i = 0; i < n; i++) {
        cin >> words[i];
        int cur = 0;
        for (char c : words[i]) {
            if (t[cur].next[c - 'a'] == -1) {
                t[cur].next[c - 'a'] = t.size();
                t.emplace_back();
            }
            cur = t[cur].next[c - 'a'];
        }
        t[cur].word = i;
    }
    used.assign(R, vector<bool>(C, false));
    for (int i = 0; i < R; i++)
        for (int j = 0; j < C; j++) dfs(i, j, 0);
    if (found.empty()) cout << "NONE\n";
    for (auto &w : found) cout << w << "\n";
    return 0;
}

Python solution

import sys

data = sys.stdin.read().split()
R, C = int(data[0]), int(data[1])
g = data[2 : 2 + R]
n = int(data[2 + R])
words = data[3 + R : 3 + R + n]
END = "$"
trie = {}
for w in words:
    node = trie
    for c in w:
        node = node.setdefault(c, {})
    node[END] = w
found = set()
used = [[False] * C for _ in range(R)]


def dfs(x, y, node):
    nxt = node.get(g[x][y])
    if nxt is None:
        return
    if END in nxt:
        found.add(nxt[END])
    used[x][y] = True
    for a, b in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
        if 0 <= a < R and 0 <= b < C and not used[a][b]:
            dfs(a, b, nxt)
    used[x][y] = False


for i in range(R):
    for j in range(C):
        dfs(i, j, trie)
print("\n".join(sorted(found)) if found else "NONE")

Java solution

import java.io.*;
import java.util.*;

public class Main {
    static int R, C;
    static char[][] g;
    static List<int[]> next = new ArrayList<>();
    static List<String> wordAt = new ArrayList<>();
    static boolean[][] used;
    static TreeSet<String> found = new TreeSet<>();
    static int[] dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1};

    static int newNode() {
        int[] a = new int[26];
        Arrays.fill(a, -1);
        next.add(a);
        wordAt.add(null);
        return next.size() - 1;
    }

    static void dfs(int x, int y, int node) {
        int nx = next.get(node)[g[x][y] - 'a'];
        if (nx == -1) return;
        if (wordAt.get(nx) != null) found.add(wordAt.get(nx));
        used[x][y] = true;
        for (int d = 0; d < 4; d++) {
            int a = x + dx[d], b = y + dy[d];
            if (a >= 0 && b >= 0 && a < R && b < C && !used[a][b]) dfs(a, b, nx);
        }
        used[x][y] = false;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        R = Integer.parseInt(st.nextToken());
        C = Integer.parseInt(st.nextToken());
        g = new char[R][];
        for (int i = 0; i < R; i++) g[i] = br.readLine().trim().toCharArray();
        int n = Integer.parseInt(br.readLine().trim());
        newNode();
        for (int i = 0; i < n; i++) {
            String w = br.readLine().trim();
            int cur = 0;
            for (char c : w.toCharArray()) {
                if (next.get(cur)[c - 'a'] == -1) {
                    int id = newNode();
                    next.get(cur)[c - 'a'] = id;
                }
                cur = next.get(cur)[c - 'a'];
            }
            wordAt.set(cur, w);
        }
        used = new boolean[R][C];
        for (int i = 0; i < R; i++)
            for (int j = 0; j < C; j++) dfs(i, j, 0);
        StringBuilder sb = new StringBuilder();
        if (found.isEmpty()) sb.append("NONE\n");
        for (String w : found) sb.append(w).append('\n');
        System.out.print(sb);
    }
}

Solve Word Search II online · All practice problems