@@ -4,7 +4,68 @@ import Graph from '../../../../data-structures/graph/Graph';
44import bellmanFord from '../bellmanFord' ;
55
66describe ( 'bellmanFord' , ( ) => {
7- it ( 'should find minimum paths to all vertices' , ( ) => {
7+ it ( 'should find minimum paths to all vertices for undirected graph' , ( ) => {
8+ const vertexA = new GraphVertex ( 'A' ) ;
9+ const vertexB = new GraphVertex ( 'B' ) ;
10+ const vertexC = new GraphVertex ( 'C' ) ;
11+ const vertexD = new GraphVertex ( 'D' ) ;
12+ const vertexE = new GraphVertex ( 'E' ) ;
13+ const vertexF = new GraphVertex ( 'F' ) ;
14+ const vertexG = new GraphVertex ( 'G' ) ;
15+ const vertexH = new GraphVertex ( 'H' ) ;
16+
17+ const edgeAB = new GraphEdge ( vertexA , vertexB , 4 ) ;
18+ const edgeAE = new GraphEdge ( vertexA , vertexE , 7 ) ;
19+ const edgeAC = new GraphEdge ( vertexA , vertexC , 3 ) ;
20+ const edgeBC = new GraphEdge ( vertexB , vertexC , 6 ) ;
21+ const edgeBD = new GraphEdge ( vertexB , vertexD , 5 ) ;
22+ const edgeEC = new GraphEdge ( vertexE , vertexC , 8 ) ;
23+ const edgeED = new GraphEdge ( vertexE , vertexD , 2 ) ;
24+ const edgeDC = new GraphEdge ( vertexD , vertexC , 11 ) ;
25+ const edgeDG = new GraphEdge ( vertexD , vertexG , 10 ) ;
26+ const edgeDF = new GraphEdge ( vertexD , vertexF , 2 ) ;
27+ const edgeFG = new GraphEdge ( vertexF , vertexG , 3 ) ;
28+ const edgeEG = new GraphEdge ( vertexE , vertexG , 5 ) ;
29+
30+ const graph = new Graph ( ) ;
31+ graph
32+ . addVertex ( vertexH )
33+ . addEdge ( edgeAB )
34+ . addEdge ( edgeAE )
35+ . addEdge ( edgeAC )
36+ . addEdge ( edgeBC )
37+ . addEdge ( edgeBD )
38+ . addEdge ( edgeEC )
39+ . addEdge ( edgeED )
40+ . addEdge ( edgeDC )
41+ . addEdge ( edgeDG )
42+ . addEdge ( edgeDF )
43+ . addEdge ( edgeFG )
44+ . addEdge ( edgeEG ) ;
45+
46+ const { distances, previousVertices } = bellmanFord ( graph , vertexA ) ;
47+
48+ expect ( distances ) . toEqual ( {
49+ H : Infinity ,
50+ A : 0 ,
51+ B : 4 ,
52+ E : 7 ,
53+ C : 3 ,
54+ D : 9 ,
55+ G : 12 ,
56+ F : 11 ,
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' ) ;
64+ expect ( previousVertices . A ) . toBeNull ( ) ;
65+ expect ( previousVertices . H ) . toBeNull ( ) ;
66+ } ) ;
67+
68+ it ( 'should find minimum paths to all vertices for directed graph with negative edge weights' , ( ) => {
869 const vertexS = new GraphVertex ( 'S' ) ;
970 const vertexE = new GraphVertex ( 'E' ) ;
1071 const vertexA = new GraphVertex ( 'A' ) ;
0 commit comments