|
| 1 | +import static org.junit.jupiter.api.Assertions.assertArrayEquals; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.List; |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.Map; |
| 7 | +import org.junit.jupiter.api.BeforeEach; |
| 8 | +import org.junit.jupiter.api.Test; |
| 9 | + |
| 10 | +public class DijkstraShortestPathTest { |
| 11 | + |
| 12 | + private DijkstraShortestPath dijkstra; |
| 13 | + |
| 14 | + @BeforeEach |
| 15 | + public void setUp() { |
| 16 | + dijkstra = new DijkstraShortestPath(); |
| 17 | + } |
| 18 | + |
| 19 | + @Test |
| 20 | + public void testSinglePath() { |
| 21 | + // Simple graph where the path is straightforward |
| 22 | + Map<Integer, List<int[]>> adjList = new HashMap<>(); |
| 23 | + adjList.put(0, List.of(new int[]{1, 1})); |
| 24 | + adjList.put(1, List.of(new int[]{2, 1})); |
| 25 | + adjList.put(2, List.of(new int[]{3, 1})); |
| 26 | + adjList.put(3, new ArrayList<>()); |
| 27 | + |
| 28 | + int[] result = dijkstra.shortestPath(4, adjList, 0); |
| 29 | + |
| 30 | + int[] expected = {0, 1, 2, 3}; |
| 31 | + assertArrayEquals(expected, result, "Shortest path distances should match."); |
| 32 | + } |
| 33 | + |
| 34 | + @Test |
| 35 | + public void testDisconnectedGraph() { |
| 36 | + // Graph where some nodes are unreachable |
| 37 | + Map<Integer, List<int[]>> adjList = new HashMap<>(); |
| 38 | + adjList.put(0, List.of(new int[]{1, 2})); |
| 39 | + adjList.put(1, List.of(new int[]{2, 2})); |
| 40 | + adjList.put(2, new ArrayList<>()); |
| 41 | + adjList.put(3, new ArrayList<>()); |
| 42 | + |
| 43 | + int[] result = dijkstra.shortestPath(4, adjList, 0); |
| 44 | + |
| 45 | + int[] expected = {0, 2, 4, Integer.MAX_VALUE}; // node 3 is disconnected |
| 46 | + assertArrayEquals(expected, result, "Shortest path should indicate unreachable nodes."); |
| 47 | + } |
| 48 | + |
| 49 | + @Test |
| 50 | + public void testComplexGraph() { |
| 51 | + // Complex graph with multiple paths |
| 52 | + Map<Integer, List<int[]>> adjList = new HashMap<>(); |
| 53 | + adjList.put(0, List.of(new int[]{1, 4}, new int[]{2, 1})); |
| 54 | + adjList.put(1, List.of(new int[]{3, 1})); |
| 55 | + adjList.put(2, List.of(new int[]{1, 2}, new int[]{3, 5})); |
| 56 | + adjList.put(3, new ArrayList<>()); |
| 57 | + |
| 58 | + int[] result = dijkstra.shortestPath(4, adjList, 0); |
| 59 | + |
| 60 | + int[] expected = {0, 3, 1, 4}; |
| 61 | + assertArrayEquals(expected, result, "Distances should match expected shortest path distances."); |
| 62 | + } |
| 63 | +} |
0 commit comments