File tree 2 files changed +15
-2
lines changed
src/algorithms/graph/dijkstra
2 files changed +15
-2
lines changed Original file line number Diff line number Diff line change @@ -43,7 +43,7 @@ describe('dijkstra', () => {
43
43
. addEdge ( edgeFG )
44
44
. addEdge ( edgeEG ) ;
45
45
46
- const distances = dijkstra ( graph , vertexA ) ;
46
+ const { distances, previousVertices } = dijkstra ( graph , vertexA ) ;
47
47
48
48
expect ( distances ) . toEqual ( {
49
49
H : Infinity ,
@@ -55,5 +55,11 @@ describe('dijkstra', () => {
55
55
G : 12 ,
56
56
F : 11 ,
57
57
} ) ;
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' ) ;
58
64
} ) ;
59
65
} ) ;
Original file line number Diff line number Diff line change @@ -7,6 +7,7 @@ import PriorityQueue from '../../../data-structures/priority-queue/PriorityQueue
7
7
export default function dijkstra ( graph , startVertex ) {
8
8
const distances = { } ;
9
9
const visitedVertices = { } ;
10
+ const previousVertices = { } ;
10
11
const queue = new PriorityQueue ( ) ;
11
12
12
13
// Init all distances with infinity assuming that currently we can't reach
@@ -38,6 +39,9 @@ export default function dijkstra(graph, startVertex) {
38
39
if ( queue . hasValue ( neighbor ) ) {
39
40
queue . changePriority ( neighbor , distances [ neighbor . getKey ( ) ] ) ;
40
41
}
42
+
43
+ // Remember previous vertex.
44
+ previousVertices [ neighbor . getKey ( ) ] = currentVertex ;
41
45
}
42
46
43
47
// Add neighbor to the queue for further visiting.
@@ -51,5 +55,8 @@ export default function dijkstra(graph, startVertex) {
51
55
visitedVertices [ currentVertex . getKey ( ) ] = currentVertex ;
52
56
}
53
57
54
- return distances ;
58
+ return {
59
+ distances,
60
+ previousVertices,
61
+ } ;
55
62
}
You can’t perform that action at this time.
0 commit comments