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 83 84 85 86
| class Solution { class Node { Node[] children; char ch; boolean isEnd; String word;
public Node(char ch) { this.ch = ch; children = new Node[26]; isEnd = false; word = ""; } }
public List<String> findWords(char[][] board, String[] words) { Node root = buildTree(words); Set<String> result = new HashSet<>(); boolean[][] isUsed = new boolean[board.length][board[0].length]; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { find(board, i, j, root, result, isUsed); } }
return new ArrayList<>(result); }
private void find(char[][] board, int i, int j, Node root, Set<String> result, boolean[][] isUsed) { if (root.isEnd) { result.add(root.word); } if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || isUsed[i][j]) { return; } int index = board[i][j] - 'a'; if (root.children[index] == null) { return; }
isUsed[i][j] = true;
find(board, i + 1, j, root.children[index], result, isUsed); find(board, i - 1, j, root.children[index], result, isUsed); find(board, i, j + 1, root.children[index], result, isUsed); find(board, i, j - 1, root.children[index], result, isUsed);
isUsed[i][j] = false; }
private Node buildTree(String[] words) { Node root = new Node('#'); for (String word : words) { Node current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); if (current.children[ch - 'a'] == null) { current.children[ch - 'a'] = new Node(ch); }
current = current.children[ch - 'a']; }
current.isEnd = true; current.word = word; }
return root; } }
|