-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.js
More file actions
60 lines (49 loc) · 1.13 KB
/
BFS.js
File metadata and controls
60 lines (49 loc) · 1.13 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
module.exports = function (startNode, endNode, height, width, maze) {
startNode.start = true;
endNode.end = true;
const visited = new Set();
const queue = [];
queue.push(startNode);
while (queue.size !== 0) {
const node = queue.pop();
if (node.end) {
return node;
}
visited.add(node);
const sNodes = getSrroundingNodes(node, height, width, maze);
for (let sNode of sNodes) {
if (visited.has(sNode)) {
continue;
}
sNode.parent = node;
queue.push(sNode);
}
}
};
function getSrroundingNodes(node, height, width, maze) {
const nodes = [];
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
if (
(j == 0 && i == 0) ||
(i == -1 && j == -1) ||
(i == -1 && j == 1) ||
(i == 1 && j == -1) ||
(i == 1 && j == 1)
)
continue;
let dx = node.x + i;
let dy = node.y + j;
if (
dx < 0 ||
dy < 0 ||
dx > height - 1 ||
dy > width - 1 ||
maze[dx][dy].isWall
)
continue;
nodes.push(maze[dx][dy]);
}
}
return nodes;
}