这个题解使用了字典树(Trie)和深度优先搜索(DFS)的方法来解决单词搜索问题。首先,将所有需要搜索的单词构建成一棵字典树。然后,对于网格中的每个字符,从该字符开始进行DFS搜索。在DFS过程中,沿着字典树匹配字符,同时在网格上向四个方向扩展。如果在字典树的某个节点匹配到完整的单词,就将该单词加入到输出结果中。为了避免重复访问网格上的字符,使用一个visited数组来记录已访问过的位置。
时间复杂度: O(m*n*4^w + k*w)
空间复杂度: O(k*w)
```python
dirs = [(0, -1), (0, 1), (-1, 0), (1, 0)]
class TrieNode:
def __init__(self):
self.children = {} #{letter:trienode of subtree}
self.is_word = False
self.word = None
class Trie:
def __init__(self):
self.root = TrieNode()
def add(self, word): #字典树插入单词
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode() #在此节点申请节点
node = node.children[c] #继续遍历
node.is_word = True
node.word = word #存入单词
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 []
trie = Trie()
for w in words: #建立字典树,将所有dict中word放入字典树
trie.add(w)
output = []
for i in range(len(board)):
for j in range(len(board[0])):
c = board[i][j]
#从字典树root开始搜索
self.dfs(board,trie.root.children.get(c),i,j,[[i,j]],output)
return output
def dfs(self,board,node,x,y,visited,output):
if not node:
return
if node.is_word and node.word not in output:
output.append(node.word)
for d in dirs:
new_x = x+d[0]
new_y = y+d[1]
if new_x<0 or new_x>=len(board) or new_y<0 or new_y>=len(board[0]):
continue
if [new_x,new_y] in visited:
continue
visited.append([new_x,new_y])
self.dfs(board,node.children.get(board[new_x][new_y]),new_x,new_y,visited,output)
visited.pop()
```