forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0212-word-search-ii.js
102 lines (79 loc) · 2.48 KB
/
0212-word-search-ii.js
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* @param {character[][]} board
* @param {string[]} words
* Time O((ROWS * COLS) * (4 * (3 ^ (WORDS - 1)))) | Space O(N)
* @return {string[]}
*/
var findWords = function (board, words) {
return new Trie(words).searchBoard(board);
};
class TrieNode {
constructor() {
this.children = {};
this.word = '';
}
}
class Trie {
constructor(words) {
this.root = new TrieNode();
words.forEach((word) => this.insert(word));
}
/* Time O(N) | Space O(N) */
insert(word, node = this.root) {
for (const char of word) {
const child = node.children[char] || new TrieNode();
node.children[char] = child;
node = child;
}
node.word = word;
}
/* Time O((ROWS * COLS) * (4 * (3 ^ (WORDS - 1)))) | Space O(N) */
searchBoard(board, node = this.root, words = []) {
const [rows, cols] = [board.length, board[0].length];
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
this.dfs(board, row, rows, col, cols, node, words);
}
}
return words;
}
dfs(board, row, rows, col, cols, node, words) {
const char = board[row][col];
const child = node.children[char] || null;
if (this.canSkip(char, child)) return;
node = child;
this.checkWord(node, words);
this.backTrack(board, row, rows, col, cols, node, words);
}
canSkip(char, child) {
const hasSeen = char === '#';
const isMissingChild = !child;
return hasSeen || isMissingChild;
}
checkWord(node, words) {
if (!node.word.length) return;
words.push(node.word);
node.word = '';
}
backTrack(board, row, rows, col, cols, node, words) {
const char = board[row][col];
board[row][col] = '#';
for (const [_row, _col] of this.getNeighbors(row, rows, col, cols)) {
this.dfs(board, _row, rows, _col, cols, node, words);
}
board[row][col] = char;
}
getNeighbors(row, rows, col, cols) {
return [
[row - 1, col],
[row + 1, col],
[row, col - 1],
[row, col + 1],
].filter(([_row, _col]) => !this.isOutOfBounds(_row, rows, _col, cols));
}
isOutOfBounds(row, rows, col, cols) {
const isRowOut = row < 0 || rows <= row;
const isColOut = col < 0 || cols <= col;
return isRowOut || isColOut;
}
}