Word Search II
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"]class TrieNode {
private TrieNode[] list;
private int R = 26;
public String word;
public TrieNode() {
this.list = new TrieNode[R];
word = null;
}
public boolean containsKey(char c){
return list[c - 'a'] != null;
}
public void put(char c, TrieNode node){
list[c - 'a'] = node;
}
public TrieNode get(char c){
return list[c - 'a'];
}
}
class Trie{
public TrieNode root;
public Trie(){
root = new TrieNode();
}
public void insert(String word){
TrieNode node = root;
for(char c: word.toCharArray()){
if(!node.containsKey(c)){
node.put(c,new TrieNode());
}
node = node.get(c);
}
node.word = word;
}
}
class Solution {
public int[] dx = {0,0,1,-1};
public int[] dy = {1,-1,0,0};
public void search(char[][] board, int x, int y, TrieNode root, List<String> res){
if(!root.containsKey(board[x][y])) return;
TrieNode child = root.get(board[x][y]);
if(child.word != null){
if(!res.contains(child.word))
res.add(child.word);
}
char c = board[x][y];
board[x][y] = '#';
for(int i = 0; i < 4; i++){
int cx = x + dx[i];
int cy = y + dy[i];
if(!isValid(cx,cy,board)) continue;
search(board, cx, cy, child,res);
}
board[x][y] = c;
}
public boolean isValid(int x, int y,char[][] board){
if(x < 0 || x >= board.length || y < 0 || y >= board[0].length) return false;
if(board[x][y] == '#') return false;
return true;
}
public List<String> findWords(char[][] board, String[] words) {
List<String> res = new ArrayList<>();
Trie tree = new Trie();
for(String word: words){
tree.insert(word);
}
for(int i = 0; i < board.length;i++){
for(int j = 0; j < board[0].length; j++){
search(board, i, j, tree.root, res);
}
}
return res;
}
}PreviousSmallest Difference pair of values between two unsorted ArraysNextImplement Trie (Prefix Tree)
Last updated