[leetcode trie]212. Word Search II
Posted wilderness
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 162. 寻找峰值(二分)/ 212. 单词搜索 II(Trie字典树) / 36. 有效的数独
leetcode 212. Word Search II Add to List 查找单词---------- java
[leetcode]Trie-720. Longest Word in Dictionary
[leetcode trie]211. Add and Search Word - Data structure design