Luke a Pro

Luke Sun

Developer & Marketer

đŸ‡ș🇩

A* Search Algorithm

| , 4 minutes reading.

A* Search: The Scale of Dreams and Reality

The Story: Giving “Shakey” a Brain

In the late 1960s, researchers at SRI International were building Shakey, the first general-purpose mobile robot capable of reasoning about its actions. Shakey needed to move through a complex world of rooms and hallways.

The existing tools were insufficient. Dijkstra was too slow—it explored in all directions like a growing circle, wasting energy on paths leading away from the goal. The team (Peter Hart, Nils Nilsson, and Bertram Raphael) realized that if the robot knew where it was going, it should use that “dream” to guide its steps. They combined Dijkstra’s mathematical rigor with a “Heuristic”—an educated guess—and created A*. It was the birth of modern heuristic search.

Why do we need it?

Imagine driving from Paris to Berlin.

  • Dijkstra would explore roads leading to London, Marseille, and even the Atlantic Ocean, just because they are “close” to Paris.
  • A* keeps its eyes on Berlin. It prioritizes roads that actually point East.

In engineering, A* is the go-to choice for Game AI and GPS Navigation because it dramatically reduces the number of paths the computer needs to examine.

How the Algorithm “Balances”

The secret of A* is a simple but profound equation: f(n)=g(n)+h(n)f(n) = g(n) + h(n).

The algorithm acts like a traveler constantly looking at two things:

  1. g(n)g(n) (The Reality): “How much did it cost to get here from the start?” This is the hard data of the past.
  2. h(n)h(n) (The Dream): “How far is it likely to be from here to the finish?” This is the Heuristic. We don’t know the exact answer yet, so we use a straight-line distance (as the crow flies).

In every step, A* doesn’t just pick the “closest” node. It picks the node where Reality + Dream is the lowest.

If the dream (hh) is 0, it becomes Dijkstra. If the dream is too big, it might lie to you and find a bad path. But if the dream is admissible (it never overestimates the real distance), A* is guaranteed to find the perfect shortest path while ignoring 90% of the useless map.

Engineering Context: The “Compass” Choice

A* is the most popular pathfinding algorithm in the world, but it requires a Heuristic function. Choosing the right one is the engineer’s most important task:

  • Euclidean Distance: Perfect for open-world games where you can move in any direction.
  • Manhattan Distance: Best for city grids or puzzles where you only move Up/Down/Left/Right.

A* is the “Smart” choice. It is faster than Dijkstra and more accurate than pure greedy search. It is the gold standard for any system where the destination is known.

Implementation (Python)

import heapq

def a_star(graph, start, goal, heuristic):
    # g_score: Cost from start to current node (Reality)
    g_score = {node: float('inf') for node in graph}
    g_score[start] = 0
    
    # f_score: Reality + Dream (Estimated total cost)
    f_score = {node: float('inf') for node in graph}
    f_score[start] = heuristic(start, goal)
    
    # Priority Queue stores: (f_score, node_id)
    pq = [(f_score[start], start)]

    while pq:
        _, current = heapq.heappop(pq)

        if current == goal:
            return g_score[goal] # Destination reached!

        for neighbor, weight in graph[current].items():
            tentative_g = g_score[current] + weight
            
            # If this new path to neighbor is better than any previous one
            if tentative_g < g_score[neighbor]:
                g_score[neighbor] = tentative_g
                f_score[neighbor] = tentative_g + heuristic(neighbor, goal)
                heapq.heappush(pq, (f_score[neighbor], neighbor))

    return float('inf')

# Example Heuristic: Straight-line distance
# def manhattan_dist(p1, p2):
#     return abs(p1.x - p2.x) + abs(p1.y - p2.y)

Summary

A* teaches us that knowing the past is important, but having a vision for the future is what makes us efficient. By balancing the weight of our steps with the direction of our goals, A* finds the optimal path through the chaos of the real world.