212. Word Search II
bfs/dfs
题干:
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
解释:
从这个矩阵中找到所有的字典中的单词。
思考:
类似搜索的题,核心的问题就是,如何减少重复计算。比如这个题,假如我们使用dfs,我们每次到达一个点都要重复计算这个点后面有什么点,非常的麻烦。所以对这个题,我们要首先创建所有可能的路径,也就是创建字典树,之后在字典树上运行dfs,这样就可以大大减少重复和不必要的分支了。 答案是一个大佬写的python,非常简洁,清晰明了,值得在面试中使用
答案:
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
trie={}
for word in words:
node = trie
for char in word:
#这个函数的意思是插入这个值,并且返回值;如果key不存在,就插入;如果已经存在就返回
node = node.setdefault(char,{})
#这里是标志这个节点是末尾节点
node['#']=True
def search(i,j,node,pre,visited):
if '#' in node:
res.add(pre)
for (di,dj) in ((-1,0),(1,0),(0,-1),(0,1)):
ii=i+di
jj=j+dj
if -1<ii<h and -1<jj<w and board[ii][jj] in node and (ii,jj) not in visited:
search(ii,jj,node[board[ii][[jj]]],pre+board[ii][jj],visited | {(ii,jj)})
res, h, w = set(),len(board),len(board[0])
for i in range(h):
for i in range(w):
if board[i][j] in trie:
search(i,j,trie[board[i][j]],board[i][j],{(i,j)})
return list(res)
答案补充:
只要20行就能实现java 100 行的内容,这就是python的价值