← Blog

A* Search Algorithm Explained with Example (Python Code)

By Umar Shakar · 15 Nov 2026 · Artificial Intelligence

On this page

Every time a delivery app plans a route or a game character walks around a wall, some search algorithm is quietly doing the work. The one you will meet most often is the A* search algorithm. It is old, it is simple to code, and it is still the default choice for pathfinding in a huge number of products.

In my work as a web developer I mostly build websites, but routing questions come up more than you might expect: store locators, "nearest branch" features, and small logistics dashboards for clients. In this guide I explain A* from the ground up, compare it with the simpler searches it grew out of, and walk through a small example on a made-up Abu Dhabi road map with Python code you can run yourself.

The problem: finding a good route without checking every road

Imagine you need to drive from the Corniche to Yas Island. There are many possible routes. You could list every single one and pick the shortest, but on a real map that number explodes very quickly. What you want is a method that finds the shortest route while looking at as few roads as possible.

Computer scientists describe this kind of task as a state-space search. Before choosing an algorithm, you write the problem down in five parts:

This framing comes straight from the standard AI textbook by Russell and Norvig, Artificial Intelligence: A Modern Approach. Once a problem is written this way, every search algorithm below works on it without changes. The only thing that differs is the order in which they explore.

Four ways to search, from blind to informed

Breadth-first search (BFS)

BFS explores one "layer" at a time: all places one road away, then all places two roads away, and so on. It always finds the route with the fewest roads. That is not the same as the shortest distance. A route with two long motorways beats a route with three short streets in BFS's eyes, even if it is twice the distance. BFS is only optimal when every step costs the same.

Uniform cost search (UCS)

UCS fixes that by always expanding the place with the lowest total cost so far, called g(n). It is guaranteed to find the cheapest route as long as costs are positive. If you have heard of Dijkstra's algorithm, UCS is essentially the same idea used to reach one goal. The weakness is that UCS has no sense of direction. It spreads out evenly in every direction, including away from the goal.

Greedy best first search goes to the other extreme. It ignores the distance already travelled and always moves to the place that looks closest to the goal, using an estimate called a heuristic, h(n). A typical heuristic for maps is the straight-line distance. Greedy search is often fast, but it can be fooled into a long route because it never looks back at what it has already spent.

A* combines both ideas. For every place it scores:

f(n) = g(n) + h(n)

Here g(n) is the real cost from the start to n, and h(n) is the estimated cost from n to the goal. A* always expands the place with the lowest f. The algorithm was published by Hart, Nilsson and Raphael in 1968 (Hart et al., 1968), and the core idea has hardly changed since.

Admissible heuristics: the rule that keeps A* honest

A* is only guaranteed to return the shortest route if the heuristic is admissible, which means it never overestimates the true remaining cost. Straight-line distance works for roads because no road can be shorter than a straight line.

A slightly stronger property is consistency: for any road from n to m, h(n) must be no more than the cost of that road plus h(m). A consistent heuristic is always admissible, and it means A* never needs to revisit a place it has already finished with. A heuristic of zero everywhere is admissible too, but then A* turns back into uniform cost search. The better (larger, but still admissible) your estimate, the fewer places A* has to look at.

Worked example: Corniche to Yas Island

Here is a small graph I made up for this article. The landmarks are real, but the distances are invented so the maths stays easy to follow. Do not use them for actual driving.

The heuristic values (estimated km to Yas Island) are: Corniche 24, Al Maryah 22, Saadiyat 15, Khalifa City 12, Masdar 11, Airport 7, Yas Island 0. I checked each one against the true shortest distance, and none of them overestimates, so the heuristic is admissible. It is consistent as well.

Step by step

  1. Start at the Corniche: g = 0, h = 24, so f = 24. Its neighbours go on the frontier: Al Maryah (f = 4 + 22 = 26), Saadiyat (f = 9 + 15 = 24) and Masdar (f = 20 + 11 = 31).
  2. The lowest f is Saadiyat at 24. Expanding it adds Yas Island with g = 9 + 18 = 27, so f = 27. Going back to Al Maryah through Saadiyat would cost 16, which is worse than the 4 we already have, so it is ignored.
  3. Next is Al Maryah at 26. It adds Khalifa City with f = 26 + 12 = 38.
  4. Now Yas Island has the lowest f at 27. It is the goal, so A* stops.

Result: Corniche to Saadiyat to Yas Island, 27 km, after expanding only four places. Masdar, the Airport and Khalifa City were never expanded at all.

Compare that with greedy best first search. From the Corniche, Masdar looks closest (h = 11), and from Masdar, Yas Island is right there. Greedy returns Corniche to Masdar to Yas Island, which is 34 km. It was quick, but it was wrong. Uniform cost search does find the 27 km route, but it expands all seven places on the way because it has no idea which direction Yas Island is in.

Python A* implementation

This version uses Python's built-in heapq module as a priority queue. If dictionaries are new to you, my post on Python lists and dictionaries covers the basics used here.

import heapq

# Made-up road distances in km (not real driving distances)
roads = {
    "Corniche":     {"Al Maryah": 4, "Saadiyat": 9, "Masdar": 20},
    "Al Maryah":    {"Corniche": 4, "Saadiyat": 7, "Khalifa City": 22},
    "Saadiyat":     {"Corniche": 9, "Al Maryah": 7, "Yas Island": 18},
    "Khalifa City": {"Al Maryah": 22, "Airport": 8, "Yas Island": 15},
    "Masdar":       {"Corniche": 20, "Airport": 6, "Yas Island": 14},
    "Airport":      {"Masdar": 6, "Khalifa City": 8, "Yas Island": 9},
    "Yas Island":   {"Saadiyat": 18, "Khalifa City": 15, "Masdar": 14, "Airport": 9},
}

# Straight-line guesses to Yas Island (never more than the real road distance)
h = {"Corniche": 24, "Al Maryah": 22, "Saadiyat": 15, "Khalifa City": 12,
     "Masdar": 11, "Airport": 7, "Yas Island": 0}

def a_star(start, goal):
    frontier = [(h[start], 0, start, [start])]   # (f, g, node, path)
    best_g = {start: 0}
    expanded = []
    while frontier:
        f, g, node, path = heapq.heappop(frontier)
        if g > best_g.get(node, float("inf")):
            continue                              # stale entry, skip it
        expanded.append(node)
        if node == goal:
            return path, g, expanded
        for nxt, cost in roads[node].items():
            new_g = g + cost
            if new_g < best_g.get(nxt, float("inf")):
                best_g[nxt] = new_g
                heapq.heappush(frontier, (new_g + h[nxt], new_g, nxt, path + [nxt]))
    return None, float("inf"), expanded

path, cost, expanded = a_star("Corniche", "Yas Island")
print("Route:", " -> ".join(path))
print("Distance:", cost, "km")
print("Expanded:", expanded)

Expected output:

Route: Corniche -> Saadiyat -> Yas Island
Distance: 27 km
Expanded: ['Corniche', 'Saadiyat', 'Al Maryah', 'Yas Island']

The best_g dictionary remembers the cheapest known cost to each place, so a worse route to the same landmark is skipped. The list of expanded nodes matches the hand trace above, which is a good habit: always check your code against a small example you can work out on paper.

Comparison table

AlgorithmOrders the frontier byShortest route guaranteed?Places expanded in our example
Breadth-first searchNumber of stepsOnly if all steps cost the sameDepends on order; finds a 2-road route
Uniform cost search / Dijkstrag(n)Yes (positive costs)7
Greedy best first searchh(n)No3 (but returns 34 km)
A*g(n) + h(n)Yes, with an admissible heuristic4

A* vs Dijkstra in practice

Use Dijkstra when you need the shortest distance from one place to every other place, or when you have no sensible heuristic. Use A* when you have one specific goal and a decent estimate of the remaining cost. On a grid or a road map, that estimate is usually easy to get, and the savings grow with the size of the map.

A quick look at Minimax and alpha-beta pruning

A* works when you are the only one making moves. In a two-player game such as noughts and crosses or chess, the opponent is trying to beat you, so search changes shape. Minimax assumes you pick the move with the highest score while your opponent picks the one with the lowest, and it works backwards from the end positions.

Alpha-beta pruning gives the same answer while skipping branches that cannot change the result. Here is a tiny example. You have two moves. After move A, your opponent can leave you with a score of 3 or 5, so they will choose 3. After move B, the first reply you check gives you 2. You can stop there: whatever the other replies under B are worth, your opponent can already hold you to 2, and you have a guaranteed 3 from move A. The rest of branch B is pruned. With perfect move ordering, this saving lets a game engine search up to twice as deep in the same time, a result covered in detail in AIMA's chapter on adversarial search.

Key takeaways

Frequently asked questions

What is the A* search algorithm in simple words?

It is a pathfinding method that always explores the option with the lowest "cost so far plus estimated cost to go". This keeps it pointed at the goal while still guaranteeing the shortest route.

What is the difference between A* and Dijkstra?

Dijkstra only uses the cost so far, so it searches evenly in every direction. A* adds a heuristic estimate of the remaining distance, which steers it towards the goal and usually means far fewer nodes are explored.

Is best first search the same as A*?

Not quite. Best first search is a family of methods that pick the "best looking" node by some score. Greedy best first search uses only h(n), while A* is the best first search that uses g(n) + h(n).

What happens if the heuristic overestimates?

A* may still find a route, often faster, but it is no longer guaranteed to be the shortest one.

If you would like a store locator, route planner or another smart feature built into your website, have a look at my web development and SEO services. If you are new to the language used in this guide, start with my introduction to Python.

Need a website, SEO or a custom business app?
I'm Umar, a web developer and SEO specialist in Abu Dhabi. Get in touch.