# 单词搜索 II

<p>给定一个 <code>m x n</code> 二维字符网格 <code>board</code><strong> </strong>和一个单词（字符串）列表 <code>words</code>，找出所有同时在二维网格和字典中出现的单词。</p>

<p>单词必须按照字母顺序，通过 <strong>相邻的单元格</strong> 内的字母构成，其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。</p>

<p> </p>

<p><strong>示例 1：</strong></p>
<img alt="" src="https://img-service.csdnimg.cn/img_convert/3c58915d280f9462e912c68fbe6cc128.jpeg" style="width: 322px; height: 322px;" />
<pre>
<strong>输入：</strong>board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
<strong>输出：</strong>["eat","oath"]
</pre>

<p><strong>示例 2：</strong></p>
<img alt="" src="https://img-service.csdnimg.cn/img_convert/2799340eb0a16624ef37341b8ab15fd9.jpeg" style="width: 162px; height: 162px;" />
<pre>
<strong>输入：</strong>board = [["a","b"],["c","d"]], words = ["abcb"]
<strong>输出：</strong>[]
</pre>

<p> </p>

<p><strong>提示：</strong></p>

<ul>
	<li><code>m == board.length</code></li>
	<li><code>n == board[i].length</code></li>
	<li><code>1 <= m, n <= 12</code></li>
	<li><code>board[i][j]</code> 是一个小写英文字母</li>
	<li><code>1 <= words.length <= 3 * 10<sup>4</sup></code></li>
	<li><code>1 <= words[i].length <= 10</code></li>
	<li><code>words[i]</code> 由小写英文字母组成</li>
	<li><code>words</code> 中的所有字符串互不相同</li>
</ul>


## template

```python
class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        if not board or not board[0] or not words:
            return []
        self.root = {}
        for word in words:
            node = self.root
            for char in word:
                if char not in node:
                    node[char] = {}
                node = node[char]
            node["#"] = word
        res = []
        for i in range(len(board)):
            for j in range(len(board[0])):
                tmp_state = []
                self.dfs(i, j, board, tmp_state, self.root, res)
        return res

    def dfs(self, i, j, board, tmp_state, node, res):
        if "#" in node and node["#"] not in res:
            res.append(node["#"])
        if [i, j] not in tmp_state and board[i][j] in node:
            tmp = tmp_state + [[i, j]]
            candidate = []
            if i - 1 >= 0:
                candidate.append([i - 1, j])
            if i + 1 < len(board):
                candidate.append([i + 1, j])
            if j - 1 >= 0:
                candidate.append([i, j - 1])
            if j + 1 < len(board[0]):
                candidate.append([i, j + 1])
            node = node[board[i][j]]
            if "#" in node and node["#"] not in res:
                res.append(node["#"])
            for item in candidate:
                self.dfs(item[0], item[1], board, tmp, node, res)

```

## 答案

```python

```

## 选项

### A

```python

```

### B

```python

```

### C

```python

```