|
| 1 | +package algorithms; |
| 2 | + |
| 3 | +import com.baeldung.algorithms.dijkstra.Dijkstra; |
| 4 | +import com.baeldung.algorithms.dijkstra.Graph; |
| 5 | +import com.baeldung.algorithms.dijkstra.Node; |
| 6 | +import org.junit.Test; |
| 7 | + |
| 8 | +import java.util.Arrays; |
| 9 | +import java.util.List; |
| 10 | + |
| 11 | +import static org.junit.Assert.assertTrue; |
| 12 | + |
| 13 | +public class DijkstraAlgorithmTest { |
| 14 | + |
| 15 | + @Test |
| 16 | + public void whenSPPSolved_thenCorrect() { |
| 17 | + |
| 18 | + Node nodeA = new Node("A"); |
| 19 | + Node nodeB = new Node("B"); |
| 20 | + Node nodeC = new Node("C"); |
| 21 | + Node nodeD = new Node("D"); |
| 22 | + Node nodeE = new Node("E"); |
| 23 | + Node nodeF = new Node("F"); |
| 24 | + |
| 25 | + nodeA.addDestination(nodeB, 10); |
| 26 | + nodeA.addDestination(nodeC, 15); |
| 27 | + |
| 28 | + nodeB.addDestination(nodeD, 12); |
| 29 | + nodeB.addDestination(nodeF, 15); |
| 30 | + |
| 31 | + nodeC.addDestination(nodeE, 10); |
| 32 | + |
| 33 | + nodeD.addDestination(nodeE, 2); |
| 34 | + nodeD.addDestination(nodeF, 1); |
| 35 | + |
| 36 | + nodeF.addDestination(nodeE, 5); |
| 37 | + |
| 38 | + Graph graph = new Graph(); |
| 39 | + |
| 40 | + graph.addNode(nodeA); |
| 41 | + graph.addNode(nodeB); |
| 42 | + graph.addNode(nodeC); |
| 43 | + graph.addNode(nodeD); |
| 44 | + graph.addNode(nodeE); |
| 45 | + graph.addNode(nodeF); |
| 46 | + |
| 47 | + graph = Dijkstra.calculateShortestPathFromSource(graph, nodeA); |
| 48 | + |
| 49 | + List<Node> shortestPathForNodeB = Arrays.asList(nodeA); |
| 50 | + List<Node> shortestPathForNodeC = Arrays.asList(nodeA); |
| 51 | + List<Node> shortestPathForNodeD = Arrays.asList(nodeA, nodeB); |
| 52 | + List<Node> shortestPathForNodeE = Arrays.asList(nodeA, nodeB, nodeD); |
| 53 | + List<Node> shortestPathForNodeF = Arrays.asList(nodeA, nodeB, nodeD); |
| 54 | + |
| 55 | + for (Node node : graph.getNodes()) { |
| 56 | + switch (node.getName()) { |
| 57 | + case "B": |
| 58 | + assertTrue(node |
| 59 | + .getShortestPath() |
| 60 | + .equals(shortestPathForNodeB)); |
| 61 | + break; |
| 62 | + case "C": |
| 63 | + assertTrue(node |
| 64 | + .getShortestPath() |
| 65 | + .equals(shortestPathForNodeC)); |
| 66 | + break; |
| 67 | + case "D": |
| 68 | + assertTrue(node |
| 69 | + .getShortestPath() |
| 70 | + .equals(shortestPathForNodeD)); |
| 71 | + break; |
| 72 | + case "E": |
| 73 | + assertTrue(node |
| 74 | + .getShortestPath() |
| 75 | + .equals(shortestPathForNodeE)); |
| 76 | + break; |
| 77 | + case "F": |
| 78 | + assertTrue(node |
| 79 | + .getShortestPath() |
| 80 | + .equals(shortestPathForNodeF)); |
| 81 | + break; |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | +} |
0 commit comments