#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Home / Blog /

A* Algorithm in AI

Heuristic Search for Pathfinding

Published
6 min read
Scroll Down

What is the A* algorithm?

A* (read "A-star") is an informed search algorithm that finds the lowest-cost path from a start node to a goal node in a weighted graph. It was introduced by Hart, Nilsson and Raphael in 1968 and is still the standard choice for pathfinding in games, robotics and route planning.

For every node n on the frontier, A* computes

f(n) = g(n) + h(n)
  • g(n): the actual cost of the best path found so far from the start to n.
  • h(n): a heuristic estimate of the cost from n to the goal, for example the straight-line distance on a map.
  • f(n): the estimated cost of the cheapest complete path that goes through n.

A* always expands the frontier node with the smallest f(n). With h(n) = 0 it becomes uniform-cost search (Dijkstra's algorithm); if it ignored g(n) and used only h(n), it would become greedy best-first search. Combining both is what makes A* both fast and optimal.

A* algorithm: steps

  1. Put the start node on the OPEN list with g = 0 and f = h(start). The CLOSED list is empty.
  2. If OPEN is empty, stop: there is no path.
  3. Remove the node n with the lowest f from OPEN. If n is the goal, stop and rebuild the path by following parent pointers back to the start.
  4. Move n to CLOSED. For each successor m of n with edge cost c(n, m):
    • compute the new cost g' = g(n) + c(n, m);
    • if m is not on OPEN or CLOSED, or g' is lower than its current g(m), set g(m) = g', f(m) = g' + h(m), parent(m) = n, and put m on OPEN (with an inconsistent heuristic, this can move a node back from CLOSED to OPEN).
  5. Go back to step 2.

The goal test happens when a node is removed from OPEN, not when it is first generated. Testing on generation can return a path that is not the cheapest.

Worked example: A* on a weighted graph

Find the cheapest path from S to G. Every h value is at most the true remaining cost, so the heuristic is admissible.

Edges (directed, with costs)        Heuristic h(n)
S -> A  1      A -> C  5            h(S) = 7
S -> B  4      A -> G 12            h(A) = 6
A -> B  2      B -> C  2            h(B) = 4
               C -> G  3            h(C) = 2
                                    h(G) = 0
StepNode expanded (f)Successors: g, fOPEN after stepNote
1S (7)A: 1, 7 · B: 4, 8A(7), B(8)
2A (7)B: 3, 7 · C: 6, 8 · G: 13, 13B(7), C(8), G(13)B found more cheaply via A (3 < 4), parent of B becomes A
3B (7)C: 5, 7C(7), G(13)C improves from 6 to 5 via B
4C (7)G: 8, 8G(8)G improves from 13 to 8 via C
5G (8)--Goal removed from OPEN: stop

Path: S → A → B → C → G, cost 8. Notice that G was generated in step 2 with cost 13 through the direct edge A → G. A* did not stop there, because a node with a lower f value (B, f = 7) was still on OPEN. That is exactly why the goal test is done on removal.

A* in Python (graph and grid)

The function below works for any problem: you pass a neighbors function that yields (next node, step cost) pairs and a heuristic h. It uses heapq as the OPEN list. Instead of updating entries inside the heap, it pushes a new entry when it finds a cheaper path and skips stale entries when they are popped, which is the usual way to implement A* in Python.

import heapq

def a_star(start, goal, neighbors, h):
    """neighbors(n) yields (next_node, step_cost); h(n) estimates cost from n to goal."""
    open_heap = [(h(start), 0, start)]          # entries: (f, g, node)
    g = {start: 0}
    parent = {start: None}
    closed = set()
    while open_heap:
        f, cost, node = heapq.heappop(open_heap)
        if node in closed:
            continue                            # stale entry: a cheaper copy was already expanded
        if node == goal:
            path = []
            while node is not None:
                path.append(node)
                node = parent[node]
            return path[::-1], cost
        closed.add(node)
        for nxt, step in neighbors(node):
            new_g = cost + step
            if nxt not in g or new_g < g[nxt]:  # found a cheaper way to nxt
                g[nxt] = new_g
                parent[nxt] = node
                heapq.heappush(open_heap, (new_g + h(nxt), new_g, nxt))
    return None, float('inf')

# Example 1: weighted graph with a heuristic table
edges = {'S': [('A', 1), ('B', 4)], 'A': [('B', 2), ('C', 5), ('G', 12)],
         'B': [('C', 2)], 'C': [('G', 3)], 'G': []}
h_table = {'S': 7, 'A': 6, 'B': 4, 'C': 2, 'G': 0}
print(a_star('S', 'G', lambda n: edges[n], lambda n: h_table[n]))

# Example 2: 4 x 4 grid, walls marked '#', moves up/down/left/right cost 1
grid = ["S...",
        ".##.",
        "....",
        "#..G"]
def grid_neighbors(cell):
    r, c = cell
    for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        nr, nc = r + dr, c + dc
        if 0 <= nr < 4 and 0 <= nc < 4 and grid[nr][nc] != '#':
            yield (nr, nc), 1
manhattan = lambda cell: abs(cell[0] - 3) + abs(cell[1] - 3)
print(a_star((0, 0), (3, 3), grid_neighbors, manhattan))

Output:

(['S', 'A', 'B', 'C', 'G'], 8)
([(0, 0), (0, 1), (0, 2), (0, 3), (1, 3), (2, 3), (3, 3)], 6)

The first result matches the hand trace. The second solves a 4 × 4 grid with walls, using Manhattan distance |Δrow| + |Δcolumn| as the heuristic. On a grid with only up, down, left and right moves of cost 1, Manhattan distance never overestimates, so the path of length 6 is the shortest one.

Admissible and consistent heuristics

  • Admissible: h(n) never overestimates the true cost from n to the goal. With an admissible heuristic, A* (with re-opening of closed nodes when needed) always returns an optimal path.
  • Consistent (monotone): for every edge n → m, h(n) ≤ c(n, m) + h(m). A consistent heuristic is also admissible, and with it a node never needs to be reopened once it is on CLOSED, so the simple version of the algorithm is optimal. The heuristic in the example is consistent; check, for example, h(A) = 6 ≤ 2 + h(B) = 6.
  • Better-informed is faster: if h1(n) ≤ h2(n) for all n and both are admissible, A* with h2 never expands more nodes. For the 8-puzzle, the sum of Manhattan distances of the tiles beats the number of misplaced tiles for this reason.
  • Overestimating (for example, multiplying h by a weight greater than 1) usually makes the search faster but can return a longer path. This trade-off is called weighted A*.

Designing such estimates is covered in more depth in heuristic search techniques.

Complexity, advantages and limitations

  • Time: exponential in the worst case, O(bd) for branching factor b and solution depth d. A good heuristic cuts this down sharply; with h = 0 the search is the same as uniform-cost search.
  • Space: also O(bd), because A* keeps every generated node in memory. On large maps, memory usually runs out before time does. Variants such as IDA* (iterative deepening A*) and SMA* (simplified memory-bounded A*) address this.
  • Complete on finite graphs, and on infinite graphs where every edge cost is at least some positive ε.
  • Needs a heuristic: the quality of the result and the speed depend on h. Without one, use Dijkstra's algorithm.
AlgorithmExpands the node with lowestOptimal?
Uniform-cost search (Dijkstra)g(n)Yes, for non-negative edge costs
Greedy best-first searchh(n)No
A*g(n) + h(n)Yes, with an admissible heuristic
AO*Revised cost of a solution graph (AND-OR graphs)Yes, with an admissible heuristic on acyclic graphs

A* searches ordinary OR graphs. When problems split into subproblems that must all be solved, the AO* algorithm extends the same idea to AND-OR graphs. For the uninformed methods A* improves on, see BFS and DFS in AI; for a classic puzzle to practise on, try the water jug problem. Search algorithms including A* are part of the problem-solving module in Uncodemy's Artificial Intelligence course.