Photo AI

Last Updated Sep 27, 2025

The A* Algorithm Simplified Revision Notes

Revision notes with simplified explanations to understand The A* Algorithm quickly and effectively.

user avatar
user avatar
user avatar
user avatar
user avatar

211+ students studying

The A* Algorithm

Overview

A* is a graph traversal and pathfinding algorithm widely used in computer science for finding the shortest path from a source node to a target node. It is an enhancement of Dijkstra's algorithm that incorporates heuristics to optimise the search process, making it more efficient in certain scenarios.

How A Algorithm Works*

  • Inputs:

    • A weighted graph or grid.
    • A source node (start) and a target node (goal).
  • Outputs:

    • The shortest path from the source to the target, if it exists. A* uses a combination of:
  • g(n): The cost from the start node to the current node.

  • h(n): A heuristic estimate of the cost from the current node to the target node.

  • f(n) = g(n) + h(n): The total estimated cost of the cheapest path through the current node. Steps:

  1. Initialise the open set (nodes to be evaluated) with the start node.
  2. Track the costs and previous nodes for backtracking the path.
  3. While the open set is not empty:
  • Select the node with the lowest f(n) value.
  • If this node is the target, reconstruct and return the path.
  • Otherwise, evaluate its neighbours:
  • Update g(n) for each neighbour.
  • Recalculate f(n).
  • If a shorter path to a neighbour is found, update it.
  • Move the current node to the closed set (evaluated nodes).
  1. Repeat until the target is reached or all nodes are evaluated.

Heuristic Function

The heuristic h(n) plays a critical role in guiding the algorithm:

Manhattan Distance: Used in grids where movement is restricted to horizontal and vertical.

h(n)=x1x2+y1y2h(n) = |x_1 - x_2| + |y_1 - y_2|

Euclidean Distance: Used when diagonal movement is allowed.

h(n)=(x1x2)2+(y1y2)2h(n) = \sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}

The heuristic must be admissible (never overestimates the actual cost) and ideally consistent for optimal performance.

infoNote

Example: Finding the Shortest Path

Given a graph:

Nodes: A, B, C, D, E

Edges with weights:

  • A → B: 1

  • A → C: 4

  • B → C: 2

  • B → D: 6

  • C → D: 3

  • C → E: 5

  • D → E: 1 Heuristic (h) values (to target E):

  • A: 7, B: 6, C: 2, D: 1, E: 0 Step-by-Step Execution:

  1. Start at A:
  • g(A) = 0, h(A) = 7, f(A) = 7
  1. Evaluate neighbours B and C:
  • g(B) = 1, h(B) = 6, f(B) = 7
  • g(C) = 4, h(C) = 2, f(C) = 6
  1. Move to C (lowest f):
  • Evaluate neighbours D and E.
  • g(D) = 7, h(D) = 1, f(D) = 8
  • g(E) = 9, h(E) = 0, f(E) = 9
  1. Move to B (next lowest f):
  • Evaluate neighbour D.
  • g(D) = 7 (already calculated; no shorter path).
  1. Move to D:
  • Evaluate neighbour E.
  • g(E) = 8, h(E) = 0, f(E) = 8
  1. Move to E (target reached). Shortest path: A → B → D → E, Total cost = 8.

Pseudocode for A* Algorithm

METHOD AStar(graph, start, goal)
    openSet ← PRIORITY_QUEUE containing start
    cameFrom ← EMPTY_MAP
    gScore ← MAP with default value ∞
    gScore[start] ← 0
    fScore ← MAP with default value ∞
    fScore[start] ← heuristic(start, goal)

    WHILE openSet IS NOT EMPTY
        current ← node in openSet with lowest fScore
        IF current = goal
            RETURN ReconstructPath(cameFrom, current)

        REMOVE current FROM openSet
        FOR each neighbor of current
            tentative_gScore ← gScore[current] + distance(current, neighbor)
            IF tentative_gScore < gScore[neighbor]
                cameFrom[neighbor] ← current
                gScore[neighbor] ← tentative_gScore
                fScore[neighbor] ← gScore[neighbor] + heuristic(neighbor, goal)
                IF neighbor NOT IN openSet
                    ADD neighbor TO openSet
    RETURN "No Path Found"

Python Implementation

import heapq

def a_star(graph, start, goal, heuristic):
    open_set = []
    heapq.heappush(open_set, (0, start))
    came_from = {}
    g_score = {node: float('inf') for node in graph}
    g_score[start] = 0
    f_score = {node: float('inf') for node in graph}
    f_score[start] = heuristic[start]

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

        if current == goal:
            return reconstruct_path(came_from, current)

        for neighbor, weight in graph[current]:
            tentative_g_score = g_score[current] + weight
            if tentative_g_score < g_score[neighbor]:
                came_from[neighbor] = current
                g_score[neighbor] = tentative_g_score
                f_score[neighbor] = g_score[neighbor] + heuristic[neighbor]
                heapq.heappush(open_set, (f_score[neighbor], neighbor))

    return "No Path Found"

def reconstruct_path(came_from, current):
    path = []
    while current in came_from:
        path.append(current)
        current = came_from[current]
    path.reverse()
    return path

infoNote

Example: Tracing A Algorithm*

Given a grid:

Start: S, Goal: G

S115G\begin{array}{|c|c|c|c|c|} \hline S & 1 & 1 & 5 & G \\ \hline \end{array}

Step 1: Initialise.

Step 2: Expand S, and calculate costs for neighbours.

Step 3: Expand the next lowest f(n)

Repeat until goal G is reached.

Note Summary

infoNote

Common Mistakes

  1. Using a Non-Admissible Heuristic: An overestimating heuristic may cause the algorithm to miss the shortest path.
  2. Failing to Update gScore Properly: Incorrect gScore calculations can lead to incorrect path reconstruction.
  3. Not Reconstructing the Path Correctly: Ensure the cameFrom map is used to backtrack from the goal to the start.
infoNote

Key Takeaways

  • The A* Algorithm combines the best aspects of Dijkstra's and Greedy Best-First Search.
  • It uses both the actual cost ( g(n) ) and a heuristic estimate ( h(n) ).
  • Heuristic plays a critical role in guiding the search efficiently.
  • Correct implementation of priority queue and cost updates ensures optimal paths.
Books

Only available for registered users.

Sign up now to view the full note, or log in if you already have an account!

500K+ Students Use These Powerful Tools to Master The A* Algorithm

Enhance your understanding with flashcards, quizzes, and exams—designed to help you grasp key concepts, reinforce learning, and master any topic with confidence!

120 flashcards

Flashcards on The A* Algorithm

Revise key concepts with interactive flashcards.

Try Computer Science Flashcards

12 quizzes

Quizzes on The A* Algorithm

Test your knowledge with fun and engaging quizzes.

Try Computer Science Quizzes

29 questions

Exam questions on The A* Algorithm

Boost your confidence with real exam questions.

Try Computer Science Questions

27 exams created

Exam Builder on The A* Algorithm

Create custom exams across topics for better practice!

Try Computer Science exam builder

12 papers

Past Papers on The A* Algorithm

Practice past papers to reinforce exam experience.

Try Computer Science Past Papers

Other Revision Notes related to The A* Algorithm you should explore

Discover More Revision Notes Related to The A* Algorithm to Deepen Your Understanding and Improve Your Mastery

96%

114 rated

Algorithms for the Main Data Structures

Stacks

user avatar
user avatar
user avatar
user avatar
user avatar

251+ studying

191KViews

96%

114 rated

Algorithms for the Main Data Structures

Queues

user avatar
user avatar
user avatar
user avatar
user avatar

496+ studying

183KViews

96%

114 rated

Algorithms for the Main Data Structures

Trees

user avatar
user avatar
user avatar
user avatar
user avatar

399+ studying

195KViews

96%

114 rated

Algorithms for the Main Data Structures

Linked List

user avatar
user avatar
user avatar
user avatar
user avatar

319+ studying

185KViews
Load more notes

Join 500,000+ A-Level students using SimpleStudy...

Join Thousands of A-Level Students Using SimpleStudy to Learn Smarter, Stay Organized, and Boost Their Grades with Confidence!

97% of Students

Report Improved Results

98% of Students

Recommend to friends

500,000+

Students Supported

50 Million+

Questions answered