Given an m x nboard of characters and a list of strings words, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example 1:
**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"]
Example 2:
**Input:** board = [["a","b"],["c","d"]], words = ["abcb"]
**Output:** []
Constraints:
m == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j] is a lowercase English letter.
1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i] consists of lowercase English letters.
All the strings of words are unique.
ac
classSolution {publicList<String> findWords(char[][] board,String[] words) {List<String> res =newArrayList<String>();// edge casesif (board.length==0|| board[0].length==0||words.length==0) {return res; }// build trieTrieNode root =newTrieNode();root.build(words);for (int r =0; r <board.length; r++) {for (int c =0; c < board[0].length; c++) {dfs(board, r, c, root, res); } }return res; }privatevoiddfs(char[][] board,int r,int c,TrieNode node,List<String> res) {// out of boundary?if (r <0|| c <0|| r >=board.length|| c >= board[0].length) return;// visited in this word? current char not in trie? returnint pos = board[r][c] -'a';if (board[r][c] =='#'||node.next[pos] ==null) return;// continue, mark visitedchar curr = board[r][c]; board[r][c] ='#';// find wordif (node.next[pos].word!=null) {res.add(node.next[pos].word);node.next[pos].word=null; }// adjacent charsdfs(board, r+1, c,node.next[pos], res);dfs(board, r-1, c,node.next[pos], res);dfs(board, r, c+1,node.next[pos], res);dfs(board, r, c-1,node.next[pos], res);// resume visited mark board[r][c] = curr; }}classTrieNode {publicTrieNode[] next;String word;publicTrieNode() { next =newTrieNode[26]; }publicvoidinsert(String s,int index) {if (index ==s.length()) {this.word= s;return; }int i =s.charAt(index) -'a';if (next[i] ==null) next[i] =newTrieNode(); next[i].insert(s, index+1); }publicvoidbuild(String[] words){for (String w : words) {insert(w,0); } }}// build a trie, node with a string// walk board, current char in trie? continue : return;//board[r][c] - 'a'