3
Map<Character, TrieNode> children = new HashMap();9
int[][] dirs = new int[][] {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};11
public List<String> findWords(char[][] board, String[] words) {12
Set<String> res = new HashSet<>();13
TrieNode root = new TrieNode();15
int n = board[0].length;17
for (String word : words) {18
char[] cArr = word.toCharArray();19
TrieNode dummy = root;22
if (!dummy.children.containsKey(c)) {23
dummy.children.put(c, new TrieNode());25
dummy = dummy.children.get(c);31
for (int i = 0; i < m; i++) {32
for (int j = 0; j < n; j++) {33
char nextChar = board[i][j];34
boolean[][] visited = new boolean[m][n];35
if (root.children.containsKey(nextChar)) {36
res.addAll(dfs(board, root.children.get(nextChar), i, j, visited, "" + nextChar));41
return new ArrayList<>(res);44
Set<String> dfs(char[][] board, TrieNode root, int i, int j, boolean[][] visited, String word) {45
Set<String> res = new HashSet<>();54
for (int[] dir : dirs) {55
int newI = i + dir[0];56
int newJ = j + dir[1];59
&& newI < board.length61
&& newJ < board[0].length62
&& !visited[newI][newJ]) {63
char nextChar = board[newI][newJ];64
if (root.children.containsKey(nextChar)) {66
res.addAll(dfs(board, root.children.get(nextChar), newI, newJ, visited, word + nextChar));71
visited[i][j] = false;