Skip to content

Commit c97e472

Browse files
committedMay 3, 2018
Add Dijkstra.
1 parent ce7a4a9 commit c97e472

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed
 

‎src/algorithms/graph/dijkstra/__test__/dijkstra.test.js

+7-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ describe('dijkstra', () => {
4343
.addEdge(edgeFG)
4444
.addEdge(edgeEG);
4545

46-
const distances = dijkstra(graph, vertexA);
46+
const { distances, previousVertices } = dijkstra(graph, vertexA);
4747

4848
expect(distances).toEqual({
4949
H: Infinity,
@@ -55,5 +55,11 @@ describe('dijkstra', () => {
5555
G: 12,
5656
F: 11,
5757
});
58+
59+
expect(previousVertices.F.getKey()).toBe('D');
60+
expect(previousVertices.D.getKey()).toBe('B');
61+
expect(previousVertices.B.getKey()).toBe('A');
62+
expect(previousVertices.G.getKey()).toBe('E');
63+
expect(previousVertices.C.getKey()).toBe('A');
5864
});
5965
});

‎src/algorithms/graph/dijkstra/dijkstra.js

+8-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import PriorityQueue from '../../../data-structures/priority-queue/PriorityQueue
77
export default function dijkstra(graph, startVertex) {
88
const distances = {};
99
const visitedVertices = {};
10+
const previousVertices = {};
1011
const queue = new PriorityQueue();
1112

1213
// Init all distances with infinity assuming that currently we can't reach
@@ -38,6 +39,9 @@ export default function dijkstra(graph, startVertex) {
3839
if (queue.hasValue(neighbor)) {
3940
queue.changePriority(neighbor, distances[neighbor.getKey()]);
4041
}
42+
43+
// Remember previous vertex.
44+
previousVertices[neighbor.getKey()] = currentVertex;
4145
}
4246

4347
// Add neighbor to the queue for further visiting.
@@ -51,5 +55,8 @@ export default function dijkstra(graph, startVertex) {
5155
visitedVertices[currentVertex.getKey()] = currentVertex;
5256
}
5357

54-
return distances;
58+
return {
59+
distances,
60+
previousVertices,
61+
};
5562
}

0 commit comments

Comments
 (0)
Please sign in to comment.