Ai PRA4
Ai PRA4
Ai PRA4
A * Algorithm:
The A* (pronounced "A star") algorithm is a widely-used pathfinding
algorithm that finds the shortest path between two points in a weighted graph. It
combines the cost of reaching a node from the start node (known as the "g" cost) and a
heuristic estimate of the cost to reach the goal from that node (known as the "h" cost) to
guide its search. The algorithm uses a priority queue to explore nodes efficiently and
guarantees the shortest path if certain conditions are met.
Algorithm:
1. Initialize a priority queue (open set) and a set to keep track of visited nodes
(closed set).
2. Create a start node and add it to the open set. Set its "g" cost to 0.
3. While the open set is not empty:
I. Pop the node with the lowest combined cost ("g" cost + "h" cost) from
the open set.
II. If the current node is the goal node, reconstruct and return the path.
III. Otherwise, mark the current node as visited by adding it to the closed
set.
4. For each neighbor of the current node that is not in the closed set:
5. Calculate the tentative "g" cost from the start node to this neighbor.
6. If the neighbor is not in the open set or the new "g" cost is lower than the
existing one, update its "g" cost and set its parent as the current node.
7. If the neighbor is not in the open set, calculate its "h" cost (heuristic estimate
to the goal) and add it to the open set.
8. If the open set becomes empty and the goal node has not been reached, there
is no path. Exit with a "Path does not exist" message.
9. End the algorithm.
This algorithm efficiently explores the graph by prioritizing nodes with a
lower estimated cost to reach the goal. It guarantees the shortest path when
the following conditions are met:
The heuristic function "h" is admissible (never overestimates the true cost).
The graph does not have cycles with negative edge weights.
The algorithm uses a consistent heuristic (satisfies the triangle inequality).
The A* algorithm is widely used in various applications, including robotics,
video games, and route planning, where finding the shortest path is crucial.
Code:
import heapq
while open_set:
current_f, current_node = heapq.heappop(open_set)
if current_node == goal:
path = []
while current_node in parent:
path.append(current_node)
current_node = parent[current_node]
path.append(start)
path.reverse()
return path
closed_set.add(current_node)
return None
if path:
print(f"Shortest path from {start_node} to {goal_node}: {path}")
else:
print(f"No path found from {start_node} to {goal_node}")
Output: