Home / Blog /

A* Algorithm in AI

Heuristic Search for Pathfinding

Uncodemy AI Team
June 21, 2026
15 min read
Scroll Down

A* Algorithm

Overview of A* Algorithm

Explain the A* algorithm with example.

Answer:

The A* algorithm is a heuristic-based search algorithm used in AI for finding the shortest path from a start node to a goal node in a weighted graph. It combines the benefits of Dijkstra’s algorithm (guaranteed shortest path) and Greedy Best-First Search (heuristic-driven efficiency) by using a cost function f(n) = g(n) + h(n), where g(n) is the cost from the start to node n, and h(n) is the estimated cost from n to the goal. Below, we explain A*’s mechanics, properties, and an example using a grid-based pathfinding problem, addressing loop prevention.

Mechanics of A* Algorithm
  • Initialization: Start with the initial node in an open list, set g(start)=0, and compute f(start)=h(start).
  • Node Selection: Choose the node with the lowest f(n) from the open list.
  • Expansion: Generate successors, compute g(n) and h(n) for each, and update f(n).
  • Update: If a successor has a lower f(n), update its parent and costs. Move the current node to the closed list.
  • Termination: Stop when the goal node is selected or the open list is empty (no path exists).
  • Loop Prevention: Use a closed list to avoid revisiting nodes, preventing infinite cycles.
Properties
  • Completeness: Guaranteed in finite graphs with non-negative edge costs.
  • Optimality: Finds the shortest path if h(n) is admissible (never overestimates).
  • Time Complexity: O(b^d), where b is the branching factor and d is the depth, depending on heuristic quality.
  • Space Complexity: O(b^d) for storing open and closed lists.
Example: Grid Pathfinding

Consider a 4x4 grid where the goal is to move from (0,0) to (3,3). Cells have a cost of 1 to move (up, down, left, right), and some cells (e.g., (1,1), (2,1)) are obstacles. Use Manhattan distance as h(n).
- Grid: (0,0) is start, (3,3) is goal, obstacles at (1,1), (2,1).
- Heuristic: h(n) = |x_goal - x_n| + |y_goal - y_n|.
- Execution:
1. Start at (0,0): g=0, h=6, f=6. Open={(0,0,6)}.
2. Expand (0,0): Successors (0,1), (1,0). (0,1): g=1, h=5, f=6; (1,0): g=1, h=5, f=6. Open={(0,1,6), (1,0,6)}.
3. Expand (0,1): Successors (0,2), (1,1). (1,1) is obstacle. (0,2): g=2, h=4, f=6. Open={(1,0,6), (0,2,6)}.
4. Continue until (3,3) is reached with path (0,0)→(0,1)→(0,2)→(0,3)→(1,3)→(2,3)→(3,3).
Solution: Path length=6.
Loop Prevention: Closed list ensures nodes like (0,0) aren’t re-explored.

Understanding A* Algorithm

A* is widely used in AI for pathfinding in games, robotics, and navigation systems due to its efficiency and optimality when paired with an admissible heuristic.

Key Insight

A* Algorithm balances path cost (g(n)) and heuristic estimate (h(n)) to find optimal paths efficiently.

Real-World Example: In video games, A* finds the shortest path for characters avoiding obstacles.

Did You Know?

A* powers pathfinding in games like StarCraft and navigation apps like Google Maps.

Comparing A* Algorithm

The textual diagram below compares A* with other search algorithms.

Exploring A* Algorithm

Below, we explore A* and related algorithms with vibrant cards.

A* Search

Optimal pathfinding with heuristic guidance.

Dijkstra’s

Guaranteed shortest path, no heuristic.

Best-First Search

Greedy, prioritizes h(n), non-optimal.

A* Algorithm: Python Code

Below is a Python implementation of A* for the grid example.

from heapq import heappush, heappop

def a_star(grid, start, goal):
    rows, cols = len(grid), len(grid[0])
    open_list = [(0, start, [])]  # (f, node, path)
    closed = set()
    
    def h(node):
        return abs(goal[0] - node[0]) + abs(goal[1] - node[1])  # Manhattan distance
    
    while open_list:
        f, current, path = heappop(open_list)
        if current in closed:
            continue
        closed.add(current)
        
        if current == goal:
            return path + [current]
        
        x, y = current
        for dx, dy in [(0,1), (1,0), (0,-1), (-1,0)]:  # Right, down, left, up
            nx, ny = x + dx, y + dy
            if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 0:  # Valid move
                successor = (nx, ny)
                if successor not in closed:
                    g = len(path) + 1
                    f_new = g + h(successor)
                    heappush(open_list, (f_new, successor, path + [current]))
    
    return None

grid = [
    [0, 0, 0, 0],
    [0, 1, 0, 0],
    [0, 1, 0, 0],
    [0, 0, 0, 0]
]
start, goal = (0,0), (3,3)
path = a_star(grid, start, goal)
print("Path:", path if path else "No path")
                    

This code finds the shortest path from (0,0) to (3,3), avoiding obstacles.

Technical Insights for Students

Mastering A* enhances your AI programming skills:

  • Heuristic Design: Ensure h(n) is admissible for optimality.
  • Loop Prevention: Use closed list to avoid redundant exploration.
  • Implementation: Use priority queues for efficient node selection.
  • Practical Tip: Implement A* in a maze game using Colab.

Key Takeaways

  • A* is optimal for pathfinding with admissible heuristics.
  • Balances g(n) and h(n) for efficiency.
  • Closed list prevents loops.
  • Key for games, robotics, and navigation.

Ready to Master AI Search Algorithms?

Join Uncodemy’s AI Certification Program to learn A* and other techniques.

Start Learning Today

Uncodemy Learning Platform

Popular Courses

Uncodemy AI Expert

About the Author

Dr. Sarah Johnson is Uncodemy's lead AI instructor with 10+ years of experience in machine learning and neural networks. She has worked with leading tech companies and now focuses on training the next generation of AI professionals.