Heuristics and A-star
A heuristic is an estimate that helps a search algorithm decide which state to explore. In route planning, h(n) estimates the remaining travel cost from state n to the goal. Greedy best-first search uses h alone; A-star (A*) combines the cost already paid, g(n), with h(n). Their goal is to spend less search effort, not to learn from examples.
Calculate the next priority
Imagine two waiting paths: P has g=2 and h=5; Q has g=4 and h=1. Uniform-cost search prefers P (2 < 4), greedy search prefers Q (1 < 5), and A* prefers Q because f=g+h gives P=7 and Q=5. All three quantities must use the same cost unit. The estimate is not an actual edge or a probability.
A route where the closest-looking room is misleading
A fictional cart starts at S and seeks G. The directed edges are S→A (4), S→B (1), B→A (1), A→G (4). X is isolated. Heuristic values for S,A,B,G,X are 0,0,5,0,0. Every state is declared, costs are nonnegative integers, and room labels capture all information needed for the next move. Greedy selects A (h=0), then G (h=0), costing 8. It never compares that completed route with the cheaper path through B.
from heapq import heappush, heappopfrom itertools import count
def greedy(graph, h, start, goal): serial = count() heap = [(h[start], next(serial), 0, [start])] seen = {start} while heap: _, _, cost, path = heappop(heap) node = path[-1] if node == goal: return cost, path for neighbor, weight in graph[node].items(): if neighbor not in seen: seen.add(neighbor) heappush(heap, (h[neighbor], next(serial), cost + weight, path + [neighbor])) return None
graph = {'S': {'A': 4, 'B': 1}, 'A': {'G': 4}, 'B': {'A': 1}, 'G': {}, 'X': {}}h = {'S': 0, 'A': 0, 'B': 5, 'G': 0, 'X': 0}print(greedy(graph, h, "S", "G"))print(greedy(graph, h, "S", "X"))Expected output: (8, ['S', 'A', 'G']) then None. The heap removes the smallest heuristic; a serial counter resolves ties in insertion order. The seen set prevents cycling. Marking states once is appropriate here for reachability, not for finding the cheapest route. A finite graph with this cycle handling is exhaustively searchable; unrestricted infinite search need not terminate.
A* and better paths to an old state
A* instead uses f=g+h. The first A has f=4, and B has f=6, so A is expanded first and inserts G with cost 8. Next B produces A at cost 2; A must be queued again with f=2. The new G has f=6. A* returns only when the goal is removed from the heap. A permanently closed set would miss this improvement. The best dictionary records cheapest discovered costs; outdated heap entries are skipped.
from heapq import heappush, heappopfrom itertools import count
def astar(graph, h, start, goal): serial = count() heap = [(h[start], next(serial), 0, [start])] best = {start: 0} while heap: _, _, cost, path = heappop(heap) node = path[-1] if cost != best[node]: continue if node == goal: return cost, path for neighbor, weight in graph[node].items(): new_cost = cost + weight if neighbor not in best or new_cost < best[neighbor]: best[neighbor] = new_cost heappush(heap, (new_cost + h[neighbor], next(serial), new_cost, path + [neighbor])) return None
graph = {'S': {'A': 4, 'B': 1}, 'A': {'G': 4}, 'B': {'A': 1}, 'G': {}, 'X': {}}h = {'S': 0, 'A': 0, 'B': 5, 'G': 0, 'X': 0}print(astar(graph, h, "S", "G"))print(astar(graph, h, "X", "X"))Expected output: (6, ['S', 'B', 'A', 'G']) and (0, ['X']). The second call has start equal to goal. The path is copied for clarity; large implementations usually store parent links. Heap operations and memory consumption depend on the number of improvements and frontier size.
Admissibility and consistency are different
For this lesson, an admissible heuristic is nonnegative and never exceeds the true minimum remaining cost h*(n); at the goal it is zero. An unreachable goal has infinite true cost. Consistency adds a local triangle inequality h(u) ≤ cost(u,v)+h(v) for every edge. Here h(B)=5 is admissible because the true remaining cost is 5, but inconsistent on B→A because 5 > 1+0. Thus reopening is necessary. A consistent heuristic with zero at the goal is admissible on this graph; an admissible heuristic need not be consistent.
On finite graphs with nonnegative costs, full state identity, finite nonnegative admissible estimates, strict improvement and reopening, this A* returns a minimum-cost path or None if unreachable. With a consistent heuristic a settled state need not reopen. Zero estimates reduce A* to uniform-cost search. If h(B)=100, the example returns the expensive direct-through-A route, because admissibility has been broken. In unbounded search additional conditions such as finite branching and a positive lower bound on edge costs are needed for standard termination guarantees.
Practice and common mistakes
Do not stop when a goal is first generated. Do not compare distance in meters with travel time in seconds. Do not assume a useful heuristic is always faster: computing estimates and reopening states can cost time. Trace the heap after expanding B. Change h to all zeros, predict the resulting cost, then set h(B)=100 and explain the change. Compare estimated cost with actual cost independently before trusting a new heuristic.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Heuristics and A-star — understanding check
Apply the search strategy and explain its assumptions.
P has g=2,h=5 and Q has g=4,h=1. Which does A* remove first?
Why can greedy best-first search return the cost-8 route on the cart graph?
Why does the lesson A* queue A again after expanding B?
In the cart graph, the true remaining cost from B is 5. Given h(B)=5, h(A)=0 and edge B→A of cost 1, how does h(B) compare with the admissibility bound and this edge’s consistency inequality?
What does A* become when all estimates are zero?