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.
Example:
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"]
Note:
You may assume that all inputs are consist of lowercase letters a-z.
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;
}
}