File tree Expand file tree Collapse file tree 2 files changed +15
-2
lines changed
src/algorithms/graph/dijkstra Expand file tree Collapse file tree 2 files changed +15
-2
lines changed Original file line number Diff line number Diff 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} ) ;
Original file line number Diff line number Diff line change @@ -7,6 +7,7 @@ import PriorityQueue from '../../../data-structures/priority-queue/PriorityQueue
77export 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}
You can’t perform that action at this time.
0 commit comments