A* Algorithm
Algorithm Description
A* (A-star) algorithm is a popular heuristic search algorithm used to find the shortest path from a start node to a goal node in a weighted graph. It combines elements of Dijkstra’s algorithm with a heuristic to guide the search, typically using the Euclidean distance or Manhattan distance as the heuristic function, ensuring an efficient average time complexity of O(E + V log V) in typical cases.
C++ Code
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
#define INF numeric_limits<int>::max()
#define V 6
struct Node {
int vertex, cost;
};
struct Compare {
bool operator()(const Node& a, const Node& b) {
return a.cost > b.cost;
}
};
vector<int> astar(vector<vector<pair<int, int>>>& graph, int source, int target) {
vector<int> dist(V, INF);
priority_queue<Node, vector<Node>, Compare> pq;
vector<bool> visited(V, false);
pq.push({source, 0});
dist[source] = 0;
while (!pq.empty()) {
int u = pq.top().vertex;
pq.pop();
if (visited[u]) continue;
visited[u] = true;
for (auto& edge : graph[u]) {
int v = edge.first;
int weight = edge.second;
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.push({v, dist[v]});
}
}
}
return dist;
}
int main() {
vector<vector<pair<int, int>>> graph(V);
graph[0].push_back({1, 4});
graph[0].push_back({2, 1});
graph[1].push_back({3, 1});
graph[2].push_back({1, 2});
graph[2].push_back({3, 5});
graph[3].push_back({4, 3});
graph[4].push_back({5, 2});
graph[5].push_back({3, 1});
int source = 0;
int target = 5;
vector<int> distances = astar(graph, source, target);
cout << "Shortest distances from source vertex " << source << ":\n";
for (int i = 0; i < V; ++i) {
cout << "Vertex " << i << ": " << distances[i] << "\n";
}
return 0;
}
Time and Space Complexity
Operation | Time Complexity | Space Complexity |
---|---|---|
Initialization | O(V) | O(V + E) |
A* Algorithm | O(E + V log V) | O(V) |
Where:
- V: Number of vertices in the graph.
- E: Number of edges in the graph.