|
| 1 | +package com.thealgorithms.backtracking; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.Test; |
| 4 | +import static org.junit.jupiter.api.Assertions.*; |
| 5 | +import java.util.*; |
| 6 | + |
| 7 | +public class AStarAlgorithmTest { |
| 8 | + |
| 9 | + @Test |
| 10 | + public void testBasicGraphWithManhattanHeuristic() { |
| 11 | + Graph graph = new Graph(4); |
| 12 | + graph.addEdge(0, 1, 1); |
| 13 | + graph.addEdge(1, 2, 1); |
| 14 | + graph.addEdge(2, 3, 1); |
| 15 | + graph.addEdge(0, 3, 10); |
| 16 | + |
| 17 | + int[] xCoords = {0, 1, 2, 3}; |
| 18 | + int[] yCoords = {0, 0, 0, 0}; |
| 19 | + |
| 20 | + Heuristic manhattanHeuristic = new ManhattanHeuristic(xCoords, yCoords); |
| 21 | + AStar aStar = new AStar(graph, manhattanHeuristic); |
| 22 | + |
| 23 | + List<Integer> path = aStar.findShortestPath(0, 3); |
| 24 | + |
| 25 | + List<Integer> expectedPath = Arrays.asList(0, 1, 2, 3); |
| 26 | + assertEquals(expectedPath, path); |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + public void testBasicGraphWithEuclideanHeuristic() { |
| 31 | + Graph graph = new Graph(4); |
| 32 | + graph.addEdge(0, 1, 2); |
| 33 | + graph.addEdge(1, 2, 2); |
| 34 | + graph.addEdge(2, 3, 2); |
| 35 | + graph.addEdge(0, 3, 5); |
| 36 | + |
| 37 | + int[] xCoords = {0, 2, 4, 6}; |
| 38 | + int[] yCoords = {0, 0, 0, 0}; |
| 39 | + |
| 40 | + Heuristic euclideanHeuristic = new EuclideanHeuristic(xCoords, yCoords); |
| 41 | + AStar aStar = new AStar(graph, euclideanHeuristic); |
| 42 | + |
| 43 | + List<Integer> path = aStar.findShortestPath(0, 3); |
| 44 | + |
| 45 | + List<Integer> expectedPath = Arrays.asList(0, 3); |
| 46 | + assertEquals(expectedPath, path); |
| 47 | + } |
| 48 | + |
| 49 | + @Test |
| 50 | + public void testDisconnectedGraph() { |
| 51 | + Graph graph = new Graph(4); |
| 52 | + graph.addEdge(0, 1, 2); |
| 53 | + graph.addEdge(1, 2, 2); |
| 54 | + |
| 55 | + int[] xCoords = {0, 2, 4, 6}; |
| 56 | + int[] yCoords = {0, 0, 0, 0}; |
| 57 | + |
| 58 | + Heuristic manhattanHeuristic = new ManhattanHeuristic(xCoords, yCoords); |
| 59 | + AStar aStar = new AStar(graph, manhattanHeuristic); |
| 60 | + |
| 61 | + List<Integer> path = aStar.findShortestPath(0, 3); |
| 62 | + |
| 63 | + assertTrue(path.isEmpty()); |
| 64 | + } |
| 65 | +} |
0 commit comments