Skip to content

Commit f4be952

Browse files
authored
Implementation of DijkstraAlgorithm (codesONLY#78)
1 parent cd72027 commit f4be952

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

DSA/Graphs/DijkstraAlgorithm.js

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
const graphInfo = {
2+
source: {A: 4, B: 1},
3+
A: {C: 3, D: 5},
4+
B: {A: 7, D: 2},
5+
C: {D: 4, destination: 3},
6+
D: {destination: 2},
7+
destination: {}
8+
};
9+
10+
// primary function
11+
const dijkstra = (graph) => {
12+
13+
// shortest distance to each vertex
14+
const distance = Object.assign(
15+
{destination: Infinity}, graph.source);
16+
17+
// display path
18+
const parentArray = {destination: null};
19+
for (let child in graph.source) {
20+
parentArray[child] = 'source';
21+
}
22+
23+
// track vertexs that are marked
24+
const marked = [];
25+
26+
let vertex = minimumDistancevertex(distance, marked);
27+
28+
while (vertex) {
29+
let cost = distance[vertex];
30+
let children = graph[vertex];
31+
for (let n in children) {
32+
let latestDistance = cost + children[n];
33+
if (!distance[n]) {
34+
distance[n] = latestDistance;
35+
parentArray[n] = vertex;
36+
}
37+
if (distance[n] > latestDistance) {
38+
distance[n] = latestDistance;
39+
parentArray[n] = vertex;
40+
}
41+
}
42+
marked.push(vertex);
43+
vertex = minimumDistancevertex(distance, marked);
44+
}
45+
46+
let shortestPath = ['destination'];
47+
let parent = parentArray.destination;
48+
while (parent) {
49+
shortestPath.push(parent);
50+
parent = parentArray[parent];
51+
}
52+
shortestPath.reverse();
53+
54+
const result = {
55+
distance: distance.destination,
56+
path: shortestPath
57+
};
58+
59+
return result;
60+
};
61+
62+
const minimumDistancevertex = (distance, marked) => {
63+
return Object.keys(distance).reduce((lowest, vertex) => {
64+
if (lowest === null || distance[vertex] < distance[lowest]) {
65+
if (!marked.includes(vertex)) {
66+
lowest = vertex;
67+
}
68+
}
69+
return lowest;
70+
}, null);
71+
};
72+
73+
console.log(dijkstra(graphInfo));

0 commit comments

Comments
 (0)