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 =
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"]
.
Note:
You may assume that all inputs are consist of lowercase letters
You may assume that all inputs are consist of lowercase letters
a-z
.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?
If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
Solution:
This problem is one of the hardest problem if you didn't do prefix tree before.
The idea here is build a prefix tree for the list of words, and search the prefix tree rather than individual word is much more efficient if the list of words share lots of common prefix.
For example, searching "abcde" and "abcdf" individually should require two rounds of dfs of the entire board. While with prefix tree, it can be done in one round.
public class Solution {
public class TrieNode{
public char c;
public TrieNode[] children;
public String word;
public TrieNode(char c){
c=c;
children=new TrieNode[26];
word=null;
}
}
public class Trie{
public TrieNode head;
public Trie(){
head=new TrieNode('#');
}
public void insertWord(String word){
TrieNode cur=head;
for(int i=0;i<word.length();i++){
int ind=word.charAt(i)-'a';
if(cur.children[ind]==null){
cur.children[ind]=new TrieNode(word.charAt(i));
}
cur=cur.children[ind];
}
cur.word=word;
}
}
public List<String> findWords(char[][] board, String[] words) {
Trie tr=new Trie();
List<String> res=new ArrayList<String>();
for(int i=0;i<words.length;i++){
tr.insertWord(words[i]);
}
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
helper(board,i,j,tr.head,res);
}
}
return res;
}
public void helper(char[][] board, int i, int j, TrieNode cur,List<String> res){
if(i<0 || i>=board.length || j<0 || j>=board[0].length) return;
char temp=board[i][j];
if(temp=='#'|| cur.children[temp-'a']==null) return;
board[i][j]='#';
if(cur.children[temp-'a'].word!=null){
res.add(cur.children[temp-'a'].word);
cur.children[temp-'a'].word=null;
}
helper(board,i+1,j,cur.children[temp-'a'],res);
helper(board,i-1,j,cur.children[temp-'a'],res);
helper(board,i,j+1,cur.children[temp-'a'],res);
helper(board,i,j-1,cur.children[temp-'a'],res);
board[i][j]=temp;
}
}
No comments:
Post a Comment