-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstra.js
More file actions
47 lines (37 loc) · 1.01 KB
/
dijkstra.js
File metadata and controls
47 lines (37 loc) · 1.01 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
const dijkstra = graph => {
let distances = {};
let parent = {};
let nodeList = new Set();
Object.keys(graph).forEach(key => {
nodeList.add(key);
distances[key] = Infinity;
parent[key] = null;
});
distances['a'] = 0;
while (nodeList.size > 0) {
let nodeKey = getSmallestNode(nodeList, distances);
nodeList.delete(nodeKey);
let currentNode = graph[nodeKey];
currentNode.forEach(neighbor => {
if (nodeList.has(neighbor.node)) {
let newDistance = distances[nodeKey] + neighbor.dist;
if (newDistance < distances[neighbor.node]) {
distances[neighbor.node] = newDistance;
parent[neighbor.node] = nodeKey;
}
}
});
}
return parent;
}
const getSmallestNode = (nodeList, distances) => {
let smallestNode = null;
let smallestDistance = Infinity;
nodeList.forEach(node => {
if (distances[node] < smallestDistance) {
smallestNode = node;
smallestDistance = distances[node];
}
});
return smallestNode;
}