Skip to content
    Intelligentia

    SEARCH ALGORITHMS · 11 MIN

    A* Search

    A* expands the node with the lowest f(n) = g(n) + h(n): cost so far plus estimated cost to goal.

    NEURA explains

    • g(n) is the exact path cost from the start.
    • h(n) is a heuristic estimate to the goal, e.g. Manhattan distance on a grid.
    • If h never overestimates (admissible), A* returns an optimal path.

    Real world: Navigation apps estimating 'distance as the crow flies' to guide the route search.

    Watch it move

    012345

    Visit node 0 (level 0)

    1/6

    Code

    import heapq
    def a_star(start, goal, nbrs, h):
        pq, g = [(h(start), start)], {start: 0}
        while pq:
            _, u = heapq.heappop(pq)
            if u == goal: return g[u]
            for v, w in nbrs(u):
                if g[u] + w < g.get(v, float('inf')):
                    g[v] = g[u] + w
                    heapq.heappush(pq, (g[v] + h(v), v))
    Try it in the online compiler →

    Checkpoint quiz

    A heuristic that never overestimates is called…