|
| 1 | +import { dijkstra } from "../dijkstra"; |
| 2 | + |
| 3 | +describe("dijkstra", () => { |
| 4 | + |
| 5 | + const init_graph = (N: number): [number, number][][] => { |
| 6 | + let graph = Array(N); |
| 7 | + for (let i = 0; i < N; ++i) { |
| 8 | + graph[i] = []; |
| 9 | + } |
| 10 | + return graph; |
| 11 | + } |
| 12 | + |
| 13 | + const add_edge = (graph: [number, number][][], a: number, b: number, weight: number) => { |
| 14 | + graph[a].push([b, weight]); |
| 15 | + graph[b].push([a, weight]); |
| 16 | + } |
| 17 | + |
| 18 | + it("should return the correct value", () => { |
| 19 | + let graph = init_graph(9); |
| 20 | + add_edge(graph, 0, 1, 4); |
| 21 | + add_edge(graph, 0, 7, 8); |
| 22 | + add_edge(graph, 1, 2, 8); |
| 23 | + add_edge(graph, 1, 7, 11); |
| 24 | + add_edge(graph, 2, 3, 7); |
| 25 | + add_edge(graph, 2, 5, 4); |
| 26 | + add_edge(graph, 2, 8, 2); |
| 27 | + add_edge(graph, 3, 4, 9); |
| 28 | + add_edge(graph, 3, 5, 14); |
| 29 | + add_edge(graph, 4, 5, 10); |
| 30 | + add_edge(graph, 5, 6, 2); |
| 31 | + add_edge(graph, 6, 7, 1); |
| 32 | + add_edge(graph, 6, 8, 6); |
| 33 | + add_edge(graph, 7, 8, 7); |
| 34 | + expect(dijkstra(graph, 0)).toStrictEqual([0, 4, 12, 19, 21, 11, 9, 8, 14]); |
| 35 | + }); |
| 36 | + |
| 37 | + it("should return the correct value for single element graph", () => { |
| 38 | + expect(dijkstra([[]], 0)).toStrictEqual([0]); |
| 39 | + }); |
| 40 | + |
| 41 | + let linear_graph = init_graph(4); |
| 42 | + add_edge(linear_graph, 0, 1, 1); |
| 43 | + add_edge(linear_graph, 1, 2, 2); |
| 44 | + add_edge(linear_graph, 2, 3, 3); |
| 45 | + test.each([[0, [0, 1, 3, 6]], [1, [1, 0, 2, 5]], [2, [3, 2, 0, 3]], [3, [6, 5, 3, 0]]])( |
| 46 | + "correct result for linear graph with source node %i", |
| 47 | + (source, result) => { |
| 48 | + expect(dijkstra(linear_graph, source)).toStrictEqual(result); |
| 49 | + } |
| 50 | + ); |
| 51 | + |
| 52 | + let unreachable_graph = init_graph(3); |
| 53 | + add_edge(unreachable_graph, 0, 1, 1); |
| 54 | + test.each([[0, [0, 1, Infinity]], [1, [1, 0, Infinity]], [2, [Infinity, Infinity, 0]]])( |
| 55 | + "correct result for graph with unreachable nodes with source node %i", |
| 56 | + (source, result) => { |
| 57 | + expect(dijkstra(unreachable_graph, source)).toStrictEqual(result); |
| 58 | + } |
| 59 | + ); |
| 60 | +}) |
| 61 | + |
0 commit comments