实现Trie(前缀树)
方法:字典树 + 回溯
算法流程:
根据字典中的单词构建一个Trie,稍后将用于匹配过程
从每个单元开始,如果字典中存在以单元格开头的单词,就开始回溯
在递归函数调用中,探索当前的单元格周围的相邻单元格以进行下一次递归调用。在每次调用时,先检查当前遍历的
字母序列是否与字典中的任何单词匹配,这里就需要之前构建的Trie数组结构。
Python实现:
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
#前缀树+回溯
directions = [[1,0],[0,-1],[-1,0],[0,1]]
#构建Trie
trie = {
}
for word in words:
t = trie
for w in word:
t = t.setdefault(w,{
})
t['end'] = 1
#回溯
def dfs(i,j,trie,s):
c = board[i][j]
if c not in trie:return
trie = trie[c]
if 'end' in trie and trie['end'] == 1:
res.append(s + c)
trie['end'] = 0 #防止重复数组加入
board[i][j] = '#'
for x , y in directions:
newx,newy = x + i,y + j
if 0 <= newx < row and 0 <= newy < col and board[newx][newy] != '#':
dfs(newx,newy,trie,s+c)
board[i][j] = c
res = []
row,col = len(board),len(board[0])
for i in range(row):
for j in range(col):
dfs(i,j,trie,'')
return res
详细分析见:https://leetcode-cn.com/problems/word-search-ii/solution/dan-ci-sou-suo-ii-by-leetcode/