不要背诵代码,要尝试理解代码。
万变不离其宗。
public class Solution {
public List<String> findWords(char[][] board, String[] words) {
TrieNode root = constructTrie(words);
List<String> res = new ArrayList<String>();
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
dfs(board,root,res,i,j);
}
}
return res;
}
private TrieNode constructTrie(String[] words){
TrieNode root = new TrieNode();
for(String s:words){
TrieNode cur = root;
for(char c: s.toCharArray()){
if(cur.children[c-'a']==null) cur.children[c-'a'] = new TrieNode();
cur = cur.children[c-'a'];
}
cur.word = s;
}
return root;
}
private void dfs(char[][] board, TrieNode node, List<String> res,int i,int j){
char c = board[i][j];
if(c=='#') return; //used;
if(node.children[c-'a']==null) return;
node = node.children[c-'a'];
if(node.word!=null){
res.add(node.word);
node.word = null;
}
board[i][j] = '#';//used
if(i>0) dfs(board,node,res,i-1,j);
if(j>0) dfs(board,node,res,i,j-1);
if(i+1<board.length) dfs(board,node,res,i+1,j);
if(j+1<board[0].length) dfs(board,node,res,i,j+1);
board[i][j] = c;
}
class TrieNode {
public TrieNode[] children = new TrieNode[26];
public String word;
}
}