AStar class implements the A pathfinding algorithm to find the shortest path in a graph. The graph is represented using an adjacency list, and the algorithm uses a heuristic to estimate the cost to reach the destination node. Time Complexity = O(E), where E is equal to the number of edges
| 12 | * Time Complexity = O(E), where E is equal to the number of edges |
| 13 | */ |
| 14 | public final class AStar { |
| 15 | private AStar() { |
| 16 | } |
| 17 | |
| 18 | /** |
| 19 | * Represents a graph using an adjacency list. |
| 20 | */ |
| 21 | static class Graph { |
| 22 | private ArrayList<ArrayList<Edge>> graph; |
| 23 | |
| 24 | Graph(int size) { |
| 25 | this.graph = new ArrayList<>(); |
| 26 | for (int i = 0; i < size; i++) { |
| 27 | this.graph.add(new ArrayList<>()); |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | private ArrayList<Edge> getNeighbours(int from) { |
| 32 | return this.graph.get(from); |
| 33 | } |
| 34 | |
| 35 | // Add a bidirectional edge to the graph |
| 36 | private void addEdge(Edge edge) { |
| 37 | this.graph.get(edge.getFrom()).add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight())); |
| 38 | this.graph.get(edge.getTo()).add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight())); |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Represents an edge in the graph with a start node, end node, and weight. |
| 44 | */ |
| 45 | private static class Edge { |
| 46 | private int from; |
| 47 | private int to; |
| 48 | private int weight; |
| 49 | |
| 50 | Edge(int from, int to, int weight) { |
| 51 | this.from = from; |
| 52 | this.to = to; |
| 53 | this.weight = weight; |
| 54 | } |
| 55 | |
| 56 | public int getFrom() { |
| 57 | return from; |
| 58 | } |
| 59 | |
| 60 | public int getTo() { |
| 61 | return to; |
| 62 | } |
| 63 | |
| 64 | public int getWeight() { |
| 65 | return weight; |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /** |
| 70 | * Contains information about the path and its total distance. |
| 71 | */ |
nothing calls this directly
no outgoing calls
no test coverage detected