|
| 1 | +/** |
| 2 | + * <a href="https://leetcode.com/problems/word-search-ii/">week14-5. word-search-ii</a> |
| 3 | + * <li>Description: Given an m x n board of characters and a list of strings words, return all words on the board.</li> |
| 4 | + * <li>Topics: Array, String, Backtracking, Trie, Matrix</li> |
| 5 | + * <li>Time Complexity: O(M*N*4^L), Runtime 446ms </li> |
| 6 | + * <li>Space Complexity: O(K*L), Memory 44.81MB</li> |
| 7 | + * <li>Note: Refer to answer </li> |
| 8 | + */ |
| 9 | +class Solution { |
| 10 | + |
| 11 | + class TrieNode { |
| 12 | + Map<Character, TrieNode> children = new HashMap<>(); |
| 13 | + String word = null; |
| 14 | + } |
| 15 | + |
| 16 | + public List<String> findWords(char[][] board, String[] words) { |
| 17 | + TrieNode root = buildTrie(words); |
| 18 | + List<String> result = new ArrayList<>(); |
| 19 | + |
| 20 | + for (int i = 0; i < board.length; i++) { |
| 21 | + for (int j = 0; j < board[0].length; j++) { |
| 22 | + if (root.children.containsKey(board[i][j])) { |
| 23 | + TrieNode node = root.children.get(board[i][j]); |
| 24 | + findWord(board, i, j, node, result); |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + return result; |
| 30 | + } |
| 31 | + |
| 32 | + private TrieNode buildTrie(String[] words) { |
| 33 | + TrieNode root = new TrieNode(); |
| 34 | + |
| 35 | + for (String word : words) { |
| 36 | + TrieNode node = root; |
| 37 | + for (char c : word.toCharArray()) { |
| 38 | + node = node.children.computeIfAbsent(c, k -> new TrieNode()); |
| 39 | + } |
| 40 | + node.word = word; |
| 41 | + } |
| 42 | + return root; |
| 43 | + } |
| 44 | + |
| 45 | + private int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; |
| 46 | + |
| 47 | + private void findWord(char[][] board, int r, int c, TrieNode node, List<String> result) { |
| 48 | + if (node.word != null) { |
| 49 | + result.add(node.word); |
| 50 | + node.word = null; |
| 51 | + } |
| 52 | + |
| 53 | + char letter = board[r][c]; |
| 54 | + board[r][c] = '#'; |
| 55 | + |
| 56 | + for (int[] direction : directions) { |
| 57 | + int nr = r + direction[0]; |
| 58 | + int nc = c + direction[1]; |
| 59 | + |
| 60 | + if (nr < 0 || nr > board.length - 1 || nc < 0 || nc > board[0].length - 1) { |
| 61 | + continue; |
| 62 | + } |
| 63 | + if (node.children.containsKey(board[nr][nc])) { |
| 64 | + TrieNode nextNode = node.children.get(board[nr][nc]); |
| 65 | + findWord(board, nr, nc, nextNode, result); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + board[r][c] = letter; |
| 70 | + } |
| 71 | + |
| 72 | +} |
| 73 | + |
0 commit comments