-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathword-search-ii.js
More file actions
66 lines (59 loc) · 1.31 KB
/
word-search-ii.js
File metadata and controls
66 lines (59 loc) · 1.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
/**
* @param {character[][]} board
* @param {string[]} words
* @return {string[]}
*/
var findWords = function (board, words) {
const rows = board.length;
const cols = board[0].length;
// Build a Trie from the list of words
const trie = {};
for (let word of words) {
let node = trie;
for (let char of word) {
if (!node[char]) {
node[char] = {};
}
node = node[char];
}
node.isEnd = true; // Mark the end of a word
}
const result = new Set();
const visited = Array.from({ length: rows }, () => Array(cols).fill(false));
const dfs = (row, col, node, path) => {
if (node.isEnd) {
result.add(path);
}
// Out of bounds or already visited
if (
row < 0 ||
col < 0 ||
row >= rows ||
col >= cols ||
visited[row][col] ||
!node[board[row][col]]
) {
return;
}
// Explore
visited[row][col] = true;
const char = board[row][col];
for (const [dr, dc] of [
[0, 1],
[0, -1],
[1, 0],
[-1, 0],
]) {
dfs(row + dr, col + dc, node[char], path + char);
}
visited[row][col] = false;
};
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (trie[board[i][j]]) {
dfs(i, j, trie, "");
}
}
}
return Array.from(result);
};