1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| class Solution {
boolean[][] bl; Set<String> set = new HashSet<>(); int[][] xy=new int[][]{{1,0},{-1,0},{0,1},{0,-1}}; public List<String> findWords(char[][] board, String[] words) { Trie node =new Trie(); for(String word:words){ node.add(word); } int h=board.length;int w=board[0].length; bl=new boolean[h][w]; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ bl[i][j]=true; huisu(board,node,i,j,""+board[i][j]); bl[i][j]=false; } } return new ArrayList<>(set); } public void huisu(char[][] board,Trie node,int x,int y,String s){ if(node.searchWord(s)==null)return; else if(node.searchWord(s).isempty){ set.add(s); } for(int[] z:xy){ int a=x+z[0];int b=y+z[1]; if(a>=0&&b>=0&&a<board.length&&b<board[0].length){ if(!bl[a][b]){ bl[a][b]=true; huisu(board,node,a,b,s+board[a][b]); bl[a][b]=false; } } } }
class Trie{ private Trie[] children; private boolean isempty; public Trie(){ children =new Trie[26]; isempty=false; } public void add(String word){ Trie node =this; for(int i=0;i<word.length();i++){ char ch=word.charAt(i); int index=ch-'a'; if(node.children[index]==null){ node.children[index]=new Trie(); } node=node.children[index]; } node.isempty=true; } public Trie searchWord(String word){ Trie node=this; for(int i=0;i<word.length();i++){ char ch=word.charAt(i); int index=ch-'a'; if(node.children[index]==null)return null; node=node.children[index]; } return node; } } }
|