|
| 1 | +package com.thealgorithms.datastructures.graphs; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.assertArrayEquals; |
| 4 | +import static org.junit.jupiter.api.Assertions.assertThrows; |
| 5 | + |
| 6 | +import org.junit.jupiter.api.BeforeEach; |
| 7 | +import org.junit.jupiter.api.Test; |
| 8 | + |
| 9 | +public class DijkstraOptimizedAlgorithmTest { |
| 10 | + |
| 11 | + private DijkstraOptimizedAlgorithm dijkstraOptimizedAlgorithm; |
| 12 | + private int[][] graph; |
| 13 | + |
| 14 | + @BeforeEach |
| 15 | + void setUp() { |
| 16 | + graph = new int[][] { |
| 17 | + {0, 4, 0, 0, 0, 0, 0, 8, 0}, |
| 18 | + {4, 0, 8, 0, 0, 0, 0, 11, 0}, |
| 19 | + {0, 8, 0, 7, 0, 4, 0, 0, 2}, |
| 20 | + {0, 0, 7, 0, 9, 14, 0, 0, 0}, |
| 21 | + {0, 0, 0, 9, 0, 10, 0, 0, 0}, |
| 22 | + {0, 0, 4, 14, 10, 0, 2, 0, 0}, |
| 23 | + {0, 0, 0, 0, 0, 2, 0, 1, 6}, |
| 24 | + {8, 11, 0, 0, 0, 0, 1, 0, 7}, |
| 25 | + {0, 0, 2, 0, 0, 0, 6, 7, 0}, |
| 26 | + }; |
| 27 | + |
| 28 | + dijkstraOptimizedAlgorithm = new DijkstraOptimizedAlgorithm(graph.length); |
| 29 | + } |
| 30 | + |
| 31 | + @Test |
| 32 | + void testRunAlgorithm() { |
| 33 | + int[] expectedDistances = {0, 4, 12, 19, 21, 11, 9, 8, 14}; |
| 34 | + assertArrayEquals(expectedDistances, dijkstraOptimizedAlgorithm.run(graph, 0)); |
| 35 | + } |
| 36 | + |
| 37 | + @Test |
| 38 | + void testGraphWithDisconnectedNodes() { |
| 39 | + int[][] disconnectedGraph = { |
| 40 | + {0, 3, 0, 0}, {3, 0, 1, 0}, {0, 1, 0, 0}, {0, 0, 0, 0} // Node 3 is disconnected |
| 41 | + }; |
| 42 | + |
| 43 | + DijkstraOptimizedAlgorithm dijkstraDisconnected = new DijkstraOptimizedAlgorithm(disconnectedGraph.length); |
| 44 | + |
| 45 | + // Testing from vertex 0 |
| 46 | + int[] expectedDistances = {0, 3, 4, Integer.MAX_VALUE}; // Node 3 is unreachable |
| 47 | + assertArrayEquals(expectedDistances, dijkstraDisconnected.run(disconnectedGraph, 0)); |
| 48 | + } |
| 49 | + |
| 50 | + @Test |
| 51 | + void testSingleVertexGraph() { |
| 52 | + int[][] singleVertexGraph = {{0}}; |
| 53 | + DijkstraOptimizedAlgorithm dijkstraSingleVertex = new DijkstraOptimizedAlgorithm(1); |
| 54 | + |
| 55 | + int[] expectedDistances = {0}; // The only vertex's distance to itself is 0 |
| 56 | + assertArrayEquals(expectedDistances, dijkstraSingleVertex.run(singleVertexGraph, 0)); |
| 57 | + } |
| 58 | + |
| 59 | + @Test |
| 60 | + void testInvalidSourceVertex() { |
| 61 | + assertThrows(IllegalArgumentException.class, () -> dijkstraOptimizedAlgorithm.run(graph, -1)); |
| 62 | + assertThrows(IllegalArgumentException.class, () -> dijkstraOptimizedAlgorithm.run(graph, graph.length)); |
| 63 | + } |
| 64 | +} |
0 commit comments