您的位置:首页 > 编程语言 > Java开发

212. Word Search II(Trie)

2016-09-23 17:04 323 查看
题目:

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"]
.

查找若干个单词是否在字符矩阵中,可先将若干单词建立Trie树,然后dfs字符矩阵中的单词是否在Trie树中

public class Solution {
Set<String> res = new HashSet<String>();
int[][] dir = {{0,1},{0,-1},{1,0},{-1,0}};
public List<String> findWords(char[][] board, String[] words) {
Trie trie = new Trie();
for(String str:words)
{
trie.insert(str);
}
int n= board.length;
int m = board[0].length;
boolean map[][] = new boolean
[m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
dfs(i,j,board,"",map,trie);
}
}
return new ArrayList<String>(res);
}
private void dfs(int i,int j,char[][] board,String str,boolean map[][],Trie trie)
{
if(i<0 || i>board.length-1 || j<0 || j>board[0].length-1)return;
if(map[i][j])return;
str +=board[i][j];
if(!trie.startsWith(str))return ;
if(trie.search(str))res.add(str);
map[i][j]=true;
for(int ii=0;ii<4;ii++)
{
dfs(i+dir[ii][0],j+dir[ii][1],board,str,map,trie);
}
map[i][j]=false;
}
}
class TrieNode {
boolean isend;
HashMap<Character, TrieNode> map ;
// Initialize your data structure here.
public TrieNode() {
this.isend = false;
this.map = new HashMap<Character, TrieNode>();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Trie leetcode java