單詞搜索2:
考察知識點
前綴樹,回溯算法
思路:
1.將word存放在前綴樹中,前綴樹的結尾用符號“#”表示,且結尾“#”鍵對應的值爲word。
2.遍歷board中的每一個元素,若是這個元素未被遍歷且存在word前綴樹中,則進行下一層循環。
3.若是當前遍歷board元素對應word前綴樹的“#”。說明此元素存在board中。
代碼:
class Solution(object):
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
if len(board)==0 or len(board[0])==0 or len(words)==0:
return []
self.height,self.width=len(board),len(board[0])
trie={}
self.res=set()
for word in words:
node=trie
for w in word:
if w not in node:
node[w]={}
node=node[w]
node["#"]=word
def dfs(board,index,tree_word):
i,j=index
c=board[i][j]
if c not in tree_word or board[i][j]==None:
return
board[i][j]=None
if i-1>=0:
dfs(board,(i-1,j),tree_word[c])
if i+1<self.height:
dfs(board,(i+1,j),tree_word[c])
if j-1>=0:
dfs(board,(i,j-1),tree_word[c])
if j+1<self.width:
dfs(board,(i,j+1),tree_word[c])
board[i][j]=c
next_word=tree_word[c]
if "#" in next_word:
self.res.add(next_word["#"])
for i in range(self.height):
for j in range(self.width):
dfs(board,(i,j),trie)
return list(self.res)