-
Notifications
You must be signed in to change notification settings - Fork 0
/
word-search.js
79 lines (62 loc) · 1.58 KB
/
word-search.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
class Node {
constructor(letter, row, col) {
this.letter = letter;
this.row = row;
this.col = col;
this.siblings = [];
}
}
const exist = (board, word) => {
const paths = {};
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[0].length; j++) {
const letter = board[i][j];
board[i][j] = new Node(letter, i, j);
}
}
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[i].length; j++) {
const node = board[i][j];
if (i - 1 >= 0) {
node.siblings.push(board[i - 1][j]);
}
if (i + 1 < board.length) {
node.siblings.push(board[i + 1][j]);
}
if (j - 1 >= 0) {
node.siblings.push(board[i][j - 1]);
}
if (j + 1 < board[i].length) {
node.siblings.push(board[i][j + 1]);
}
if (paths[node.letter] == null) {
paths[node.letter] = [];
}
paths[node.letter].push(node);
}
}
const queue = paths[word.charAt(0)].map((node) => ({
node,
word: word.substring(1),
visited: [node],
}));
while (queue.length) {
const { node, word, visited } = queue.pop();
if (!word.length) {
return true;
}
const nodes = node.siblings.filter((n) =>
n.letter === word.charAt(0) && visited.indexOf(n) === -1
);
for (let i = 0; i < nodes.length; i++) {
queue.push({ node: nodes[i], word: word.substring(1), visited: [...visited, nodes[i]] });
}
}
return false;
};
const board = [
['A', 'B', 'C'],
['S', 'F', 'C'],
['A', 'D', 'E']
];
console.log(exist(board, 'ABCC'));