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.
Copy Input:
board = [
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
Copy class Solution {
static class TrieNode {
TrieNode [] children = new TrieNode [ 26 ];
String word;
}
public List < String > findWords ( char [][] board , String [] words) {
List < String > res = new ArrayList <>();
TrieNode root = buildTrie(words) ;
for ( int i = 0 ; i < board . length ; i ++ )
for ( int j = 0 ; j < board[ 0 ] . length ; j ++ )
dfs(board , i , j , root , res) ;
return res;
}
public void dfs ( char [][] board , int i , int j , TrieNode p , List < String > res) {
if (i < 0 || i >= board . length || j < 0 || j >= board[ 0 ] . length )
return ;
char c = board[i][j];
// using # to mark as visited for backtracking
if (c == '#' || p . children [c - 'a' ] == null )
return ;
p = p . children [c - 'a' ];
if ( p . word != null ) { // found one
res . add ( p . word );
p . word = null ; // backtrack step
}
// marking visited
board[i][j] = '#' ;
dfs(board , i - 1 , j , p , res) ;
dfs(board , i , j - 1 , p , res) ;
dfs(board , i + 1 , j , p , res) ;
dfs(board , i , j + 1 , p , res) ;
board[i][j] = c;
// removing visited mark
}
public TrieNode buildTrie ( String [] words) {
TrieNode root = new TrieNode() ;
for ( String w : words) {
TrieNode curr = root;
for ( char c : w . toCharArray ()) {
int i = c - 'a' ;
if ( curr . children [i] == null )
curr . children [i] = new TrieNode() ;
curr = curr . children [i];
}
curr . word = w;
}
return root;
}
}