Skip to contentKEEP THE CRAFTTHE SANCTUARY

A* Search

Order a single-goal frontier by known cost g plus a justified lower bound h. Keep g separate from priority, reopen improved states when needed, and tie the Manhattan heuristic to orthogonal unit moves.

1 practice exercise1 interview problem

Recognize it when One start-to-goal route has a useful lower-bound estimate.

Checking your account…

A* Search Code Labs

Prioritize Cost So Far Plus Heuristic

A* orders frontier states by f = g + h: exact cost g from the start plus estimated remaining cost h to the goal. The heuristic changes exploration order, not the path-cost definition.

Require an Admissible Heuristic

An admissible heuristic never overestimates the true remaining cost. A consistent heuristic additionally obeys a triangle-like inequality, making finalized-state handling simpler.

Trace A-Star Priorities

Reference
def priority_trace(costs,heuristics):
    return [[node,costs[node],heuristics[node],costs[node]+heuristics[node]] for node in sorted(costs,key=lambda node:(costs[node]+heuristics[node],node))]
Practice

Implement priority_trace(costs,heuristics). Return [node,g,h,f] sorted by f then node for matching dictionaries.

Public tests

  • Order by cost plus heuristic

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace A-Star Priorities

def priority_trace(costs,heuristics):
    return [[node,costs[node],heuristics[node],costs[node]+heuristics[node]] for node in sorted(costs,key=lambda node:(costs[node]+heuristics[node],node))]

Reopen States When Costs Improve

Store best known g separately from heap priorities. If a cheaper path reaches a state, update it and push a new entry; skip stale entries whose g no longer matches.

Find Grid Cost with A-Star

Reference
import heapq

def grid_a_star(grid,start,goal):
    rows,cols=len(grid),len(grid[0]);cost={tuple(start):0};heap=[(abs(start[0]-goal[0])+abs(start[1]-goal[1]),0,tuple(start))]
    while heap:
        _,current,node=heapq.heappop(heap)
        if current!=cost[node]:continue
        if node==tuple(goal):return current
        for dr,dc in ((1,0),(-1,0),(0,1),(0,-1)):
            neighbor=(node[0]+dr,node[1]+dc)
            if 0<=neighbor[0]<rows and 0<=neighbor[1]<cols and grid[neighbor[0]][neighbor[1]]==0:
                candidate=current+1
                if candidate<cost.get(neighbor,float("inf")):
                    cost[neighbor]=candidate;heuristic=abs(neighbor[0]-goal[0])+abs(neighbor[1]-goal[1]);heapq.heappush(heap,(candidate+heuristic,candidate,neighbor))
    return -1
Practice

Implement grid_a_star(grid,start,goal). Zero cells are open, one cells blocked; return shortest orthogonal step count or -1 using Manhattan heuristic. grid is a nonempty rectangular grid; start and goal are in-bounds open cells.

Public tests

  • Use admissible Manhattan guidance

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find Grid Cost with A-Star

import heapq

def grid_a_star(grid,start,goal):
    rows,cols=len(grid),len(grid[0]);cost={tuple(start):0};heap=[(abs(start[0]-goal[0])+abs(start[1]-goal[1]),0,tuple(start))]
    while heap:
        _,current,node=heapq.heappop(heap)
        if current!=cost[node]:continue
        if node==tuple(goal):return current
        for dr,dc in ((1,0),(-1,0),(0,1),(0,-1)):
            neighbor=(node[0]+dr,node[1]+dc)
            if 0<=neighbor[0]<rows and 0<=neighbor[1]<cols and grid[neighbor[0]][neighbor[1]]==0:
                candidate=current+1
                if candidate<cost.get(neighbor,float("inf")):
                    cost[neighbor]=candidate;heuristic=abs(neighbor[0]-goal[0])+abs(neighbor[1]-goal[1]);heapq.heappush(heap,(candidate+heuristic,candidate,neighbor))
    return -1

Follow a Wall Detour Rather Than Returning Manhattan

Run the existing grid Lab with a vertical wall. Trace the forced route down, across and back up. Distinguish the cost table from the heap’s heuristic priority at every point.

Step Executed statement State Why
Initial priority heap=[(abs(start[0]-goal[0])+abs(start[1]-goal[1]),0,tuple(start))] start=(0,0), g=0,h=2,f=2 The apparent two-step route is blocked, but 2 remains a lower bound.
Pop source _,current,node=heapq.heappop(heap) current=0, node=(0,0) The popped tuple supplies the current real path cost before neighbor candidates are computed.
First detour candidate=current+1;cost[neighbor]=candidate;heuristic=abs(neighbor[0]-goal[0])+abs(neighbor[1]-goal[1]);heapq.heappush(heap,(candidate+heuristic,candidate,neighbor)) after start expansion: (1,0) has g=1,h=3,f=4 A necessary move away from the goal increases h; optimal search must still allow it.
Around the wall _,current,node=heapq.heappop(heap);candidate=current+1;cost[neighbor]=candidate;heuristic=abs(neighbor[0]-goal[0])+abs(neighbor[1]-goal[1]);heapq.heappush(heap,(candidate+heuristic,candidate,neighbor)) after successive expansions: (2,0),(2,1),(2,2) have g=2,3,4 Open-cell checks reject both central wall cells.
Reach goal _,current,node=heapq.heappop(heap);return current goal=(0,2), current=6 The returned value is the real six-step route, not the initial heuristic 2. The return executes in the actual node==goal branch.
Print Output
print(grid_a_star([[0, 1, 0], [0, 1, 0], [0, 0, 0]], [0, 0], [0, 2])) 6

The priority-only Lab isolates g+h ordering; it does not establish heuristic admissibility. Prove the estimate under the actual moves and weights before treating a smaller f as safe guidance.

Choose A Star or Dijkstra

Choose A* when a meaningful admissible heuristic guides a single-pair search. Choose Dijkstra when no useful heuristic exists or distances to many targets are needed. With h = 0, A* is Dijkstra.

Explain It in an Interview

Say: “g is known cost, h is a lower bound on remaining cost, so f prioritizes promising states without excluding an optimal path.” State admissibility or consistency, stale entries, unreachable output, and heuristic cost.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
A* on this unit grid with ManhattanO(RC log(RC))O(RC log(RC))Manhattan is consistent and the grid has O(RC) edges; a different heuristic/model needs its own bound.
Priority-only dictionary LabO(k log(k+1))O(k log(k+1))k matching cost/heuristic keys with bounded comparison and ordinary dictionary lookup; output sorts by g+h then node. This does not certify a heuristic.

Space

O(RC) costs and frontier for this fixed-degree consistent grid. The priority-only Lab uses O(k) sorted-key and output storage.

Assumptions

  • A weak heuristic can explore most reachable cells; A* is not inherently sublinear.
  • Generic inconsistent heuristics can cause repeated expansions; the grid bound does not cover every A* implementation.

Invariants Worth Saying Aloud

  1. g records an actual discovered path cost; f=g+h is only a priority.
  2. h never exceeds the remaining optimal cost under the movement model.
  3. For an inconsistent admissible heuristic, improved states may need reopening; no permanent closed-set assumption is justified automatically.

When To Use Or Avoid A* Search

Use It When

  • Use Manhattan distance for four-direction unit-cost grid movement.
  • Use h=0 when no useful admissible heuristic is known; this gives Dijkstra’s policy.

Choose Another Tool When

  • Diagonal or discounted moves can make unscaled Manhattan overestimate.
  • A heuristic value is not the actual path cost, especially when walls cause detours.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Returning the heuristic as the route length

Manhattan 2 ignores a wall forcing a four-step detour. It is a lower bound, not a completed path.

Prevent it: Return g at a current goal pop, not h at the start.

Avoid

answer = heuristic

Use instead

answer = goal_cost

Prioritizing only h and ignoring traveled cost

Greedy best-first picks a nearly-goal state with g=9,h=1 over a cheaper promising state with g=2,h=3.

Prevent it: Use f=g+h when claiming A* path optimality.

Avoid

picked = min(states, key=lambda row: row[2])

Use instead

picked = min(states, key=lambda row: row[1] + row[2])

Applying Manhattan unchanged to diagonal moves

A diagonal unit move from (0,0) to (1,1) costs 1, while Manhattan is 2 and overestimates.

Prevent it: For eight-direction unit moves use a suitable Chebyshev lower bound instead.

Avoid

h = abs(dx) + abs(dy)

Use instead

h = max(abs(dx), abs(dy))

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.