# 212    Word Search II

## 212. [Word Search II](https://leetcode.com/problems/word-search-ii/description/)

## 1. Question

Given a 2D board and a list of words from the dictionary, find all words in the board.

Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

For example,\
Given**words**=`["oath","pea","eat","rain"]`and**board**=

```
[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
```

Return

`["eat","oath"]`.

**Note:**\
You may assume that all inputs are consist of lowercase letters`a-z`.

**hint**:

You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?

If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem:[Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/)first.

## 2. Implementation

**(1) Trie + Backtracking**

```java
class Solution {
    class TrieNode {
        char val;
        boolean isWord;
        TrieNode childNode[];

        public TrieNode() {
            childNode = new TrieNode[26];
        }
    }

    class Trie {
        TrieNode root;

        public Trie() {
            root = new TrieNode();
        }

        public void add(String word) {
            if (word == null || word.length() == 0) {
                return;
            }

            TrieNode curNode = root;

            for (char c : word.toCharArray()) {
                int index = c - 'a';

                if (curNode.childNode[index] == null) {
                    curNode.childNode[index] = new TrieNode();
                    curNode.val = c;
                }
                curNode = curNode.childNode[index];
            }
            curNode.isWord = true;
        }
    }

    public List<String> findWords(char[][] board, String[] words) {
        List<String> res = new ArrayList<>();

        if (board == null || board.length == 0 || words == null || words.length == 0) {
            return res;
        }

        Trie trie = new Trie();

        for (String word : words) {
            trie.add(word);
        }

        int m = board.length, n = board[0].length;
        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        StringBuilder word = new StringBuilder();

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                searchWord(i, j, trie.root, word, words, directions, board, res);
            }
        }
        return res;
    }

    public void searchWord(int row, int col, TrieNode node, StringBuilder word, String[] words, int[][] directions, char[][] board, List<String> res) {
        if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || board[row][col] == '#') {
            return;
        }

        char c = board[row][col];
        TrieNode curNode = node.childNode[c - 'a'];

        if (curNode == null) {
            return;
        }

        word.append(c);

        if (curNode.isWord) {
            curNode.isWord = false;
            res.add(word.toString());
        }

        board[row][col] = '#';

        for (int[] direction : directions) {
            int nextRow = row + direction[0];
            int nextCol = col + direction[1];
            searchWord(nextRow, nextCol, curNode, word, words, directions, board, res);
        }
        board[row][col] = c;
        word.setLength(word.length() - 1);
    }
}
```

## 3. Time & Space Complexity

时间复杂度O(kL) + O(mn \* 4 ^ L), k是word的个数, L是每个word的平均长度, kl是建立trie的时间。我们的回溯算法对每个board的格子都遍历一遍，每个格子有4个方向可以走，知道走到word的长度为止，所以遍历的时间是mn \* 4 ^ L，空间复杂度O(26\*L) 主要是trie的空间


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/algorithm-practice/leetcode/backtracking/212-word-search-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
