You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
This lesson covers the A (A-star) algorithm* — a heuristic-based search algorithm that finds the shortest path more efficiently than Dijkstra's in many cases. It is part of the OCR A-Level Computer Science (H446) specification, section 2.3.
A* (pronounced "A-star") is a best-first search algorithm that finds the shortest path between a start vertex and a goal vertex by combining:
The algorithm selects the next vertex to explore based on:
f(n) = g(n) + h(n)
Where f(n) is the estimated total cost of the path through vertex n.
| Feature | Dijkstra's | A* |
|---|---|---|
| Explores | All vertices (in order of distance from source) | Directed towards the goal using a heuristic |
| Heuristic | None (h(n) = 0) | Uses h(n) to guide search |
| Efficiency | Explores many unnecessary vertices | Typically explores fewer vertices |
| Finds | Shortest path to ALL vertices | Shortest path to a SPECIFIC goal |
| When h(n) = 0 | A* becomes Dijkstra's algorithm | - |
The heuristic h(n) is an estimate of the cost from vertex n to the goal. It guides the search towards the goal rather than exploring in all directions.
| Property | Description |
|---|---|
| Admissible | Never overestimates the true cost to the goal. h(n) <= actual cost. |
| Consistent (monotone) | h(n) <= cost(n, m) + h(m) for every edge (n, m). |
| Informative | Higher values (closer to actual cost) make the search more efficient. |
If h(n) is admissible (never overestimates), A* is guaranteed to find the optimal (shortest) path. If h(n) overestimates, A* may find a suboptimal path.
| Heuristic | Description | Best For |
|---|---|---|
| Straight-line distance (Euclidean) | sqrt((x2-x1)^2 + (y2-y1)^2) | Map navigation, continuous space |
| Manhattan distance | x2-x1 | |
| Zero heuristic | h(n) = 0 | Reduces to Dijkstra's (always admissible) |
function aStar(graph, start, goal, heuristic)
openList = priority queue ordered by f value
closedList = empty set
g[start] = 0
f[start] = heuristic(start, goal)
parent[start] = null
openList.add(start)
while openList is not empty
current = vertex in openList with lowest f value
if current == goal then
return reconstructPath(parent, goal)
endif
openList.remove(current)
closedList.add(current)
for each neighbour n of current
if n in closedList then
continue
endif
tentativeG = g[current] + weight(current, n)
if n not in openList OR tentativeG < g[n] then
parent[n] = current
g[n] = tentativeG
f[n] = g[n] + heuristic(n, goal)
if n not in openList then
openList.add(n)
endif
endif
next n
endwhile
return "No path found"
endfunction
Consider a graph where vertices represent locations on a map:
Vertices: S (start), A, B, C, G (goal)
Edges (with weights):
S -> A: 1 S -> B: 4
A -> B: 2 A -> C: 5
B -> G: 3
C -> G: 1
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.