-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
44 lines (39 loc) · 874 Bytes
/
utils.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
/**
* @template T
* @param {T} e
* @returns {T}
*/
export function deepCopy(e) {
return JSON.parse(JSON.stringify(e));
}
/**
*
* @param {string} startXY
* @param {string} endXY
* @param {Map<string, string[]>} graph
* @returns {false|number[]}
*/
export function bfs(startNode, endNode, graph) {
const queue = [startNode];
const came_from = new Map();
came_from.set(startNode, null);
while (queue.length > 0) {
const currentNode = queue.shift();
if (currentNode == endNode) break;
// Search side paths
graph.get(currentNode).forEach(e => {
if (!came_from.has(e)) {
queue.push(e);
came_from.set(e, currentNode);
}
});
}
let currentNode = endNode;
const path = [];
while (currentNode != startNode) {
path.push(currentNode);
currentNode = came_from.get(currentNode);
if (!currentNode) return false;
}
return path;
}