MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / AStar

Class AStar

src/main/java/com/thealgorithms/datastructures/graphs/AStar.java:14–144  ·  view source on GitHub ↗

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

Source from the content-addressed store, hash-verified

12 * Time Complexity = O(E), where E is equal to the number of edges
13 */
14public 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 */

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected