Repository navigation
Expand file tree
/
Copy pathWordSearchII.java
More file actions
81 lines (64 loc) · 2.31 KB
/
Copy pathWordSearchII.java
File metadata and controls
81 lines (64 loc) · 2.31 KB
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
package com.abn.dsalgos.datastructure.graph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WordSearchII {
int[][] DIRECTIONS = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
List<String> result = new ArrayList<>();
public List<String> findWords(char[][] board, String[] words) {
Trie root = new Trie();
int rows = board.length;
int cols = board[0].length;
boolean[][] visited = new boolean[rows][cols];
for (String word : words) {
Trie current = root;
for (char ch : word.toCharArray()) {
current.children.putIfAbsent(ch, new Trie());
current = current.children.get(ch);
}
current.word = word;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (root.children.containsKey(board[i][j])) {
matrixHelper(board, i, j, rows, cols, root, visited);
}
}
}
return result;
}
private void matrixHelper(char[][] board, int i, int j, int m, int n, Trie root, boolean[][] visited) {
Trie currentNode = root.children.get(board[i][j]);
visited[i][j] = true;
if (currentNode.word != null) {
result.add(currentNode.word);
currentNode.word = null;
}
for (int[] dir : DIRECTIONS) {
int x = i + dir[0];
int y = j + dir[1];
if (x > -1 && y > -1 && x < m && y < n &&
currentNode.children.containsKey(board[x][y]) && !visited[x][y]) {
matrixHelper(board, x, y, m, n, currentNode, visited);
}
}
visited[i][j] = false;
if (currentNode.children.isEmpty()) {
root.children.remove(board[i][j]);
}
}
public static void main(String[] args) {
char[][] board = {{'o', 'a', 'a', 'n'}, {'e', 't', 'a', 'e'}, {'i', 'h', 'k', 'r'}, {'i', 'f', 'l', 'v'}};
String[] input = {"oath", "pea", "eat", "rain"};
WordSearchII wordSearchII = new WordSearchII();
wordSearchII.findWords(board, input);
}
}
class Trie {
Map<Character, Trie> children;
String word = null;
public Trie() {
children = new HashMap<>();
}
}