-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0212-word-search-ii.ts
65 lines (53 loc) · 1.54 KB
/
0212-word-search-ii.ts
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 TrieNode {
children = new Array<string>(26);
word = false;
}
class Trie {
root = new TrieNode();
add(word: string) {
let current = this.root;
for (let c of word) {
if (!current.children[c]) current.children[c] = new TrieNode();
current = current.children[c];
}
current.word = true;
}
}
function findWords(board: string[][], words: string[]): string[] {
const trie = new Trie();
for (let word of words) {
trie.add(word);
}
const rows = board.length;
const cols = board[0].length;
const resultSet = new Set<string>();
function dfs(r: number, c: number, node: TrieNode, word: string) {
if (r < 0 || r >= rows) return;
if (c < 0 || c >= cols) return;
if (board[r][c] === '.') return;
const currentChar = board[r][c];
const currentNode = node.children[currentChar];
if (!currentNode) return;
const currentWord = word + currentChar;
if (currentNode.word) {
resultSet.add(currentWord);
}
const directions = [
[r - 1, c],
[r, c + 1],
[r + 1, c],
[r, c - 1],
];
for (let [nr, nc] of directions) {
dfs(nr, nc, currentNode, currentWord);
}
board[r][c] = '.';
board[r][c] = currentChar;
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
dfs(r, c, trie.root, '');
}
}
return [...resultSet];
};