首页 > 代码库 > [leetcode trie]212. Word Search II

[leetcode trie]212. Word Search II

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.

For example,
Given words = ["oath","pea","eat","rain"] and board =

[
  [‘o‘,‘a‘,‘a‘,‘n‘],
  [‘e‘,‘t‘,‘a‘,‘e‘],
  [‘i‘,‘h‘,‘k‘,‘r‘],
  [‘i‘,‘f‘,‘l‘,‘v‘]
]

Return ["eat","oath"].

 

题意:查找哪些单词在二维字母数组中出现

思路:1.用所有的单词建立字典树

   2.遍历二维数组中的所有位置,以这个位置开头向二维数组上下左右方向扩展的字符串是否在字典树中出现

  评论区还有一种用复数和字典树的解题方法,太帅了 

 1 class Solution(object):
 2     def findWords(self, board, words):
 3         trie = {}
 4         for w in words:
 5             cur = trie
 6             for c in w:
 7                 cur = cur.setdefault(c,{})
 8             cur[None] = None
 9         self.flag = [[False]*len(board[0]) for _ in range(len(board))]
10         self.res = set()
11         for i in range(len(board)):
12             for j in range(len(board[0])):
13                 self.find(board,trie,i,j,‘‘)
14         return list(self.res)
15         
16         
17     def find(self,board,trie,i,j,str):
18         if None in trie:
19             self.res.add(str)
20         if i<0 or i>=len(board) or j<0 or j>=len(board[0]):
21             return
22         if not self.flag[i][j] and board[i][j] in trie:
23             self.flag[i][j] = True
24             self.find(board,trie[board[i][j]],i-1,j,str+board[i][j])
25             self.find(board,trie[board[i][j]],i+1,j,str+board[i][j])
26             self.find(board,trie[board[i][j]],i,j+1,str+board[i][j])
27             self.find(board,trie[board[i][j]],i,j-1,str+board[i][j])
28             self.flag[i][j] = False
29         return 

 

[leetcode trie]212. Word Search II