class Solution { class Trie{ public Trie[] children=new Trie[26]; public boolean isWord=false; public boolean added=false; public void insert(String word) { if(word.length()==0) { isWord=true; return; } int idx=word.charAt(0)-'a'; if(children[idx]==null) children[idx]=new Trie(); children[idx].insert(word.substring(1)); } } public List<String> findWords(char[][] board, String[] words) { List<String> res=new ArrayList<String>(); Trie root=new Trie(); for(String word:words) root.insert(word); boolean[][] visited=new boolean[board.length][board[0].length]; for(int i=0;i<board.length;i++) for(int j=0;j<board[0].length;j++) search(i ,j ,"" , root, visited, board, res); return res; } private void search(int i, int j, String cur, Trie node, boolean[][] visited, char[][] board, List<String> res){ if(i<0||i>=board.length||j<0||j>=board[0].length||visited[i][j]==true) return; visited[i][j]=true; int idx=board[i][j]-'a'; Trie nc=node.children[idx]; if(nc!=null) { String str=cur+board[i][j]; if(nc.isWord==true&&nc.added==false) { res.add(str); nc.added=true; } search(i-1,j,str,nc,visited,board,res); search(i+1,j,str,nc,visited,board,res); search(i,j-1,str,nc,visited,board,res); search(i,j+1,str,nc,visited,board,res); } visited[i][j]=false; } }