|
| 1 | +import {Graph} from '../../../../data-structures/graph/graph'; |
| 2 | +import {GraphVertex} from '../../../../data-structures/graph/graphVertex'; |
| 3 | +import {GraphEdge} from '../../../../data-structures/graph/graphEdge'; |
| 4 | +import {dijkstra} from '../dijsktra'; |
| 5 | + |
| 6 | +test('should return shortest paths to vertices', () => { |
| 7 | + const graph = new Graph(true); |
| 8 | + |
| 9 | + const vertexA = new GraphVertex('A'); |
| 10 | + const vertexB = new GraphVertex('B'); |
| 11 | + const vertexC = new GraphVertex('C'); |
| 12 | + const vertexD = new GraphVertex('D'); |
| 13 | + const vertexE = new GraphVertex('E'); |
| 14 | + const vertexF = new GraphVertex('F'); |
| 15 | + const vertexG = new GraphVertex('G'); |
| 16 | + const vertexH = new GraphVertex('H'); |
| 17 | + |
| 18 | + const edgeAB = new GraphEdge(vertexA, vertexB, 4); |
| 19 | + const edgeAE = new GraphEdge(vertexA, vertexE, 7); |
| 20 | + const edgeAC = new GraphEdge(vertexA, vertexC, 3); |
| 21 | + const edgeBC = new GraphEdge(vertexB, vertexC, 6); |
| 22 | + const edgeBD = new GraphEdge(vertexB, vertexD, 5); |
| 23 | + const edgeEC = new GraphEdge(vertexE, vertexC, 8); |
| 24 | + const edgeED = new GraphEdge(vertexE, vertexD, 2); |
| 25 | + const edgeDC = new GraphEdge(vertexD, vertexC, 11); |
| 26 | + const edgeDG = new GraphEdge(vertexD, vertexG, 10); |
| 27 | + const edgeDF = new GraphEdge(vertexD, vertexF, 2); |
| 28 | + const edgeFG = new GraphEdge(vertexF, vertexG, 3); |
| 29 | + const edgeEG = new GraphEdge(vertexE, vertexG, 5); |
| 30 | + |
| 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 {dist, prev} = dijkstra(graph, vertexA); |
| 47 | + |
| 48 | + expect(dist['H']).toBe(Infinity); |
| 49 | + expect(dist['A']).toBe(0); |
| 50 | + expect(dist['B']).toBe(4); |
| 51 | + expect(dist['E']).toBe(7); |
| 52 | + expect(dist['C']).toBe(3); |
| 53 | + expect(dist['D']).toBe(9); |
| 54 | + expect(dist['G']).toBe(12); |
| 55 | + expect(dist['F']).toBe(11); |
| 56 | + |
| 57 | + expect(prev['F']).toBe('D'); |
| 58 | + expect(prev['D']).toBe('B'); |
| 59 | + expect(prev['B']).toBe('A'); |
| 60 | + expect(prev['G']).toBe('E'); |
| 61 | + expect(prev['C']).toBe('A'); |
| 62 | + expect(prev['A']).toBeUndefined(); |
| 63 | + expect(prev['H']).toBeUndefined(); |
| 64 | +}); |
0 commit comments