-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshortest-path.js
44 lines (38 loc) · 951 Bytes
/
shortest-path.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
const shortestPath = (edges, nodeA, nodeB) => {
let graph = buildGraph(edges);
let visited = new Set( [ nodeA ] );
let queue = [ [nodeA,0] ];
while(queue.length > 0){
const [node,distance] = queue.shift();
if (node === nodeB) return distance;
for (let neighber of graph[node]){
if (!visited.has(neighber)){
visited.add(neighber);
queue.push([neighber, distance + 1]);
}
}
}
return -1;
};
const buildGraph = (edges) =>{
let graph = {};
for (let edge of edges){
const [a, b] = edge;
if (!(a in graph)) graph[a] = [];
if (!(b in graph)) graph[b] = [];
graph[a].push(b);
graph[b].push(a);
}
return graph;
}
const edges = [
['w', 'x'],
['x', 'y'],
['z', 'y'],
['z', 'v'],
['w', 'v']
];
console.log(shortestPath(edges, 'w', 'z'));//2
module.exports = {
shortestPath,
};