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
| class Solution {
Set<String> set = new HashSet<>(); char[][] board; int n, m; TrieNode root = new TrieNode(); int[][] dirs = new int[][] { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } }; boolean[][] vis = new boolean[15][15];
class TrieNode { String s; TrieNode[] tns = new TrieNode[26]; }
void insert(String s) { TrieNode p = root; for (int i = 0; i < s.length(); i++) { int u = s.charAt(i) - 'a'; if (p.tns[u] == null) p.tns[u] = new TrieNode(); p = p.tns[u]; } p.s = s; }
public List<String> findWords(char[][] _board, String[] words) { board = _board; m = board.length; n = board[0].length; for (String w : words) insert(w); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int u = board[i][j] - 'a'; if (root.tns[u] != null) { vis[i][j] = true; dfs(i, j, root.tns[u]); vis[i][j] = false; } } } List<String> ans = new ArrayList<>(); for (String s : set) ans.add(s); return ans; }
void dfs(int i, int j, TrieNode node) { if (node.s != null) set.add(node.s); for (int[] d : dirs) { int dx = i + d[0], dy = j + d[1]; if (dx < 0 || dx >= m || dy < 0 || dy >= n) continue; if (vis[dx][dy]) continue; int u = board[dx][dy] - 'a'; if (node.tns[u] != null) { vis[dx][dy] = true; dfs(dx, dy, node.tns[u]); vis[dx][dy] = false; } } } }
|