The A* (A-star) algorithm is a pathfinding algorithm that finds the shortest path between a starting point and a goal point in a graph. It uses a heuristic function to estimate the cost of the remaining path from a given node to the goal, and it combines this estimate with the actual cost of the path taken so far to determine which node to explore next.
Here's some pseudocode for the A* algorithm:
code
function AStar(start, goal)
// The set of nodes that have been visited
closedSet = empty set
// The set of currently discovered nodes that are not in the closed set
openSet = empty priority queue
openSet.add(start)
// For each node, which node it can most efficiently be reached from.
// If a node can be reached from many nodes, cameFrom will eventually contain the
// most efficient previous step.
cameFrom = empty dictionary
// For each node, the cost of getting from the start node to that node.
gScore = empty dictionary
gScore[start] = 0
// For each node, the estimated total cost of getting from the start node to the goal
// by passing by that node. This value is mostly used for optimization.
fScore = empty dictionary
fScore[start] = heuristic(start, goal)
while openSet is not empty
current = openSet.pop()
if current == goal
return reconstruct_path(cameFrom, goal)
closedSet.add(current)
for each neighbor of current
if neighbor in closedSet
continue
tentative_gScore = gScore[current] + distance(current, neighbor)
if neighbor not in openSet or tentative_gScore < gScore[neighbor]
cameFrom[neighbor] = current
gScore[neighbor] = tentative_gScore
fScore[neighbor] = gScore[neighbor] + heuristic(neighbor, goal)
if neighbor not in openSet
openSet.add(neighbor)
return failure
function reconstruct_path(cameFrom, current)
total_path = [current]
while current in cameFrom
current = cameFrom[current]
total_path.append(current)
return total_path[::-1] # Return the path in reverse order
The heuristic function used in this algorithm should be admissible, meaning that it should never overestimate the actual cost of the remaining path. A common heuristic function for a grid-based graph is the Manhattan distance, which is the sum of the absolute differences in the x and y coordinates between the current node and the goal node.
I hope this helps! Let me know if you have any questions.