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