| 10 | import java.util.HashSet; |
| 11 | |
| 12 | public class BoggleSolver { |
| 13 | private static class Node { |
| 14 | private boolean isTernimal = false; |
| 15 | private Node[] children = new Node[26]; |
| 16 | } |
| 17 | |
| 18 | private final Node root; // should not be modified |
| 19 | private final int[][] dirs = { |
| 20 | { -1, -1 }, { -1, 0 }, { -1, 1 }, |
| 21 | { 0, 1 }, { 0, -1 }, |
| 22 | { 1, 1 }, { 1, 0 }, { 1, -1 } |
| 23 | }; |
| 24 | |
| 25 | // Initializes the data structure using the given array of strings as the dictionary. |
| 26 | // (You can assume each word in the dictionary contains only the uppercase letters A through Z.) |
| 27 | public BoggleSolver(String[] dictionary) { |
| 28 | root = new Node(); |
| 29 | for (String s : dictionary) |
| 30 | put(root, s); |
| 31 | } |
| 32 | |
| 33 | private void put(Node x, String key) { |
| 34 | for (char c : key.toCharArray()) { |
| 35 | if (x.children[c - 'A'] == null) |
| 36 | x.children[c - 'A'] = new Node(); |
| 37 | x = x.children[c - 'A']; |
| 38 | } |
| 39 | x.isTernimal = true; |
| 40 | } |
| 41 | |
| 42 | private boolean get(Node x, String key) { |
| 43 | for (char c : key.toCharArray()) { |
| 44 | x = x.children[c - 'A']; |
| 45 | if (x == null) return false; |
| 46 | } |
| 47 | return x.isTernimal; |
| 48 | } |
| 49 | |
| 50 | // Returns the set of all valid words in the given Boggle board, as an Iterable. |
| 51 | public Iterable<String> getAllValidWords(BoggleBoard board) { |
| 52 | HashSet<String> set = new HashSet<>(); |
| 53 | boolean[][] visited = new boolean[board.rows()][board.cols()]; |
| 54 | StringBuilder sb = new StringBuilder(); |
| 55 | |
| 56 | for (int i = 0; i < board.rows(); ++i) { |
| 57 | for (int j = 0; j < board.cols(); ++j) { |
| 58 | dfs(root, board, i, j, sb, visited, set); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | return set; |
| 63 | } |
| 64 | |
| 65 | private void dfs(Node x, BoggleBoard board, int i, int j, StringBuilder sb, boolean[][] visited, |
| 66 | HashSet<String> set) { |
| 67 | char c = board.getLetter(i, j); |
| 68 | Node next = x.children[c - 'A']; |
| 69 | if (next == null) return; |
nothing calls this directly
no outgoing calls
no test coverage detected