利用字典树思想
class TrieNode:
def __init__(self):
self.children = {}
self.Word = ''
class Solution:
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
m=len(board)
if m==0: return []
n=len(board[0])
trie=self.buildTrie(words)
self.res=[]
for i in range(m):
for j in range(n):
self.DFS(board,i,j,trie)
return self.res
def DFS(self,board,i,j,trie):
if trie.Word:
self.res.append(trie.Word)
trie.Word=''
if i<0 or i>=len(board) or j<0 or j>=len(board[0]) or not board[i][j] in trie.children:
return
tmp,board[i][j]=board[i][j],'X'
for dx,dy in zip((-1,0,1,0),(0,-1,0,1)):
self.DFS(board,i+dx,j+dy,trie.children[tmp])
board[i][j]=tmp
def buildTrie(self,words):
trie=TrieNode()
for word in words:
cur=trie
for c in word:
if c not in cur.children: cur.children[c]=TrieNode()
cur=cur.children[c]
cur.Word=word
return trie