|
| 1 | +import GraphVertex from '../../../../data-structures/graph/GraphVertex'; |
| 2 | +import GraphEdge from '../../../../data-structures/graph/GraphEdge'; |
| 3 | +import Graph from '../../../../data-structures/graph/Graph'; |
| 4 | +import bellmanFord from '../bellmanFord'; |
| 5 | + |
| 6 | +describe('bellmanFord', () => { |
| 7 | + it('should find minimum paths to all vertices', () => { |
| 8 | + const vertexS = new GraphVertex('S'); |
| 9 | + const vertexE = new GraphVertex('E'); |
| 10 | + const vertexA = new GraphVertex('A'); |
| 11 | + const vertexD = new GraphVertex('D'); |
| 12 | + const vertexB = new GraphVertex('B'); |
| 13 | + const vertexC = new GraphVertex('C'); |
| 14 | + const vertexH = new GraphVertex('H'); |
| 15 | + |
| 16 | + const edgeSE = new GraphEdge(vertexS, vertexE, 8); |
| 17 | + const edgeSA = new GraphEdge(vertexS, vertexA, 10); |
| 18 | + const edgeED = new GraphEdge(vertexE, vertexD, 1); |
| 19 | + const edgeDA = new GraphEdge(vertexD, vertexA, -4); |
| 20 | + const edgeDC = new GraphEdge(vertexD, vertexC, -1); |
| 21 | + const edgeAC = new GraphEdge(vertexA, vertexC, 2); |
| 22 | + const edgeCB = new GraphEdge(vertexC, vertexB, -2); |
| 23 | + const edgeBA = new GraphEdge(vertexB, vertexA, 1); |
| 24 | + |
| 25 | + const graph = new Graph(true); |
| 26 | + graph |
| 27 | + .addVertex(vertexH) |
| 28 | + .addEdge(edgeSE) |
| 29 | + .addEdge(edgeSA) |
| 30 | + .addEdge(edgeED) |
| 31 | + .addEdge(edgeDA) |
| 32 | + .addEdge(edgeDC) |
| 33 | + .addEdge(edgeAC) |
| 34 | + .addEdge(edgeCB) |
| 35 | + .addEdge(edgeBA); |
| 36 | + |
| 37 | + const { distances, previousVertices } = bellmanFord(graph, vertexS); |
| 38 | + |
| 39 | + expect(distances).toEqual({ |
| 40 | + H: Infinity, |
| 41 | + S: 0, |
| 42 | + A: 5, |
| 43 | + B: 5, |
| 44 | + C: 7, |
| 45 | + D: 9, |
| 46 | + E: 8, |
| 47 | + }); |
| 48 | + |
| 49 | + expect(previousVertices.H).toBeNull(); |
| 50 | + expect(previousVertices.S).toBeNull(); |
| 51 | + expect(previousVertices.B.getKey()).toBe('C'); |
| 52 | + expect(previousVertices.C.getKey()).toBe('A'); |
| 53 | + expect(previousVertices.A.getKey()).toBe('D'); |
| 54 | + expect(previousVertices.D.getKey()).toBe('E'); |
| 55 | + }); |
| 56 | +}); |
0 commit comments