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.
Example:
Input:
words = [“oath”,“pea”,“eat”,“rain”] and board =
[
[‘o’,‘a’,‘a’,‘n’],
[‘e’,‘t’,‘a’,‘e’],
[‘i’,‘h’,‘k’,‘r’],
[‘i’,‘f’,‘l’,‘v’]
]
Output: [“eat”,“oath”]
Note:
You may assume that all inputs are consist of lowercase letters a-z.
将待查找的单词存放在Trie(字典树)中,利用DFS(深度优先搜索)在board中搜索即可,每次查找成功,进行剪枝操作。
dx=[-1,1,0,0]
dy=[0,0,-1,1]
END_OF_WORD = "#"
class Solution(object):
def _dfs(self,board,i,j,cur_word,cur_dict):
cur_word += board[i][j]
cur_dict = cur_dict[board[i][j]]
if END_OF_WORD in cur_dict:
self.result.add(cur_word)
tmp,board[i][j] = board[i][j],'@' #用@标记board[i][j]是否被访问过
for k in xrange(4):
x,y=i+dx[k],j+dy[k]
if 0 <= x < self.m and 0 <= y <self.n \
and board[x][y] != '@' and board[x][y] in cur_dict:
self._dfs(board,x,y,cur_word,cur_dict)
board[i][j] = tmp #还原board
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
if not board or not board[0]:
return []
if not words:
return []
self.result = set()
root = collections.defaultdict()
#把所有的words插入字典树
for word in words:
node = root
for char in word:
node = node.setdefault(char,collections.defaultdict())
node[END_OF_WORD]=END_OF_WORD
self.m,self.n=len(board),len(board[0])
for i in xrange(self.m):
for j in xrange(self.n):
if board[i][j] in root:
self._dfs(board,i,j,"",root)
return self.result
本文介绍了一种使用深度优先搜索(DFS)与字典树(Trie)结合的方法,在二维字符板中寻找所有字典中出现的单词。算法通过递归搜索相邻字母构成的单词,并利用字典树快速匹配单词的存在。
452

被折叠的 条评论
为什么被折叠?



