|  | 
|  | 1 | +class TrieNode { | 
|  | 2 | + TrieNode[] children = new TrieNode[26]; | 
|  | 3 | + String Word; | 
|  | 4 | +} | 
|  | 5 | + | 
|  | 6 | +class Solution { | 
|  | 7 | + public List<String> findWords(char[][] board, String[] words) { | 
|  | 8 | + Set<String> result = new HashSet<>(); | 
|  | 9 | + TrieNode root = buildTrie(words); | 
|  | 10 | +  | 
|  | 11 | + for (int i = 0; i < board.length; i++) { | 
|  | 12 | + for (int j = 0; j < board[i].length; j++) { | 
|  | 13 | + dfs(board, i, j, root, result); | 
|  | 14 | + } | 
|  | 15 | + } | 
|  | 16 | +  | 
|  | 17 | + return new ArrayList<>(result); | 
|  | 18 | + } | 
|  | 19 | +  | 
|  | 20 | + private void dfs(char[][] board, int x, int y, TrieNode root, Set<String> result) { | 
|  | 21 | + if (x < 0 || y < 0 || x >= board.length || y >= board[x].length || board[x][y] == '*' || root.children[board[x][y] - 'a'] == null) { return; } | 
|  | 22 | +  | 
|  | 23 | + char currChar = board[x][y]; | 
|  | 24 | + root = root.children[currChar - 'a']; | 
|  | 25 | +  | 
|  | 26 | + if (root.Word != null) { | 
|  | 27 | + result.add(root.Word); | 
|  | 28 | + } | 
|  | 29 | +  | 
|  | 30 | + board[x][y] = '*'; | 
|  | 31 | +  | 
|  | 32 | + dfs(board, x - 1, y, root, result); | 
|  | 33 | + dfs(board, x + 1, y, root, result); | 
|  | 34 | + dfs(board, x, y - 1, root, result); | 
|  | 35 | + dfs(board, x, y + 1, root, result); | 
|  | 36 | +  | 
|  | 37 | + board[x][y] = currChar; | 
|  | 38 | + } | 
|  | 39 | +  | 
|  | 40 | + private TrieNode buildTrie(String[] words) { | 
|  | 41 | + if (words == null) { return null; } | 
|  | 42 | +  | 
|  | 43 | + TrieNode root = new TrieNode(); | 
|  | 44 | + for (String word : words) { | 
|  | 45 | + TrieNode curr = root; | 
|  | 46 | + for (char c : word.toCharArray()) { | 
|  | 47 | + int idx = c - 'a'; | 
|  | 48 | + if (curr.children[idx] == null) { | 
|  | 49 | + curr.children[idx] = new TrieNode(); | 
|  | 50 | + } | 
|  | 51 | + curr = curr.children[idx]; | 
|  | 52 | + } | 
|  | 53 | +  | 
|  | 54 | + curr.Word = word; | 
|  | 55 | + } | 
|  | 56 | +  | 
|  | 57 | + return root; | 
|  | 58 | + } | 
|  | 59 | +} | 
0 commit comments