AI voor Iedereen

Search

Search chapters and demos

🧭 Heuristic Search

With depth-first and breadth-first search from the previous chapter you can in principle solve any search problem, but neither of those two algorithms is ideal. They only count the number of actions, while in practice one action often costs more than another. And they search blindly in all directions, because they do not know where the goal is.

This chapter tackles those two limitations one at a time:

  1. 📏 Costs: first we give every action a cost, so that you can model a problem more accurately. Uniform-cost search then finds the cheapest path instead of the path with the fewest actions.
  2. 🧭 Heuristics: next we give the algorithm an estimate of how far away the goal still is. Greedy search follows that estimate and therefore finishes much sooner, but it does not always find the best path.
  3. 🌟 A*: finally, the A* algorithm combines the costs with the heuristic, to find the cheapest path quickly and with a guarantee.

📏 Path costs

Suppose you run a pizzeria whose couriers deliver meals to hungry students all over Leuven. You build a GPS app that lets the couriers find the shortest route from the restaurant to any place in the city. To do so, you model a search space in which every intersection between the main roads is a state. After all, each time you reach such an intersection, you have to choose which other road to take: that is your action. A possible action is therefore a road between two neighboring intersections. For simplicity, our app ignores one-way streets: you can take every road in both directions. Below you see an example location for the pizzeria (🍕) and the place where you have to deliver (🏠).

Loading demo

The basic search algorithms from the previous chapter, such as depth-first search and breadth-first search, treat every action (= every road between two intersections) as equally costly. The "shortest" path that breadth-first search returns therefore passes as few intersections as possible. For this search problem that is not a good solution: not every road between intersections is equally long. The route with the fewest intersections is therefore not necessarily the fastest.

You can see this in the long, winding routes that breadth-first search finds below: it avoids the straight Brusselsestraat and the Bondgenotenlaan, because they pass more intersections.

Loading demo

You want the deliveries to arrive as quickly as possible. So you make the search algorithm take into account the "cost" attached to each action. In the example of the delivery app, you label every road between two neighboring intersections (the actions) with the distance between those intersections. The map then looks like this:

Loading demo

A good search algorithm for this problem should therefore be able to find the path with the lowest path cost (in this case the total number of meters along the whole path).

Path cost Definition

The path cost g(p)g(p) of a path pp is the sum of the costs of all actions on that path.

Here pp is a specific path from the start state to a particular state, and g(p)g(p) is what that path costs in total.

But how do you adapt the search algorithm so that it can handle such costs? To solve this kind of problem, we introduce uniform-cost search.

Uniform-cost search is a smarter version of breadth-first search that takes different costs per action into account, so as to find the path with the lowest path cost. The main difference with breadth-first search lies in how the algorithm manages the frontier.

Instead of a simple queue, in which expansions are added at the back and paths are considered in order of increasing number of actions, uniform-cost search uses a priority queue as its frontier, which is always sorted by increasing path cost g(p)g(p). The path with the lowest cost is at the front, the path with the highest cost at the back. So it does not explore paths based on their length in number of actions, but based on their path cost g(p)g(p): the total cost of path p from the start state.

The name can be confusing, because here the costs per action are precisely not uniform. "Uniform" refers to the way the algorithm explores the search space: breadth-first search does so in layers of equal depth (first all paths of one action, then those of two actions, and so on), uniform-cost search in layers of equal path cost.

🫷 Priority queue

Expansions of the current path always go into the place in this priority queue that matches their cost. That way they are always in order of total path cost. It may sound like a lot of effort to sort the frontier after every expansion. Fortunately, the priority queue (external link) is a clever data structure that efficiently puts new states in the right place, without sorting the whole list again every time.

a priority queue receives three new paths on the right and puts them in the right place in the frontier on the left

A priority queue puts new paths in the right place in the queue

🌊 Difficult terrain

You can adapt the maze worlds from the previous chapter so that they also have different costs per cell. The search problem below shows a top view of a small park with a pond, grass and a low wall. Each action has a different cost, depending on the terrain of the state the action takes you to:

  • cells with 💧 water have a cost of 10
  • cells with 🌿 grass have a cost of 4
  • ⬜ empty cells have a cost of 1

Compare how uniform-cost search makes deliberate detours when some actions have a higher cost (such as grass and water), while breadth-first search ignores those costs. Breadth-first search simply goes through the water, because it only optimizes the number of actions and does not notice the higher cost. Uniform-cost search neatly walks around the whole pond and ventures neither onto the grass nor into the water, unless that really saves a good deal.

Drag the start state (🙂) one cell up: then uniform-cost search does find it worthwhile to walk through the grass, because the path cost is then 31 instead of the 32 it would cost to go around. Also watch how the frontier on the right evolves: with uniform-cost search it is always sorted by path cost (📏).

Loading demo

Notice that the paths of breadth-first search are shorter in number of actions, while those of uniform-cost search are lower in path cost. Uniform-cost search is guaranteed to find the cheapest path (the lowest path cost) to a state at the moment it first reaches that state. This is similar to how breadth-first search is guaranteed to find the shortest path (in number of actions) as soon as it first reaches a state.

🍕 Pizzeria

Now apply the same idea to the Leuven pizzeria that wants to find the shortest path to the house that ordered a meal. Below you solve the problem with uniform-cost search. Here too you see that it explores a kind of "circle" of ever longer paths in all directions. Select breadth-first search as the algorithm at the top left: here too it does not find the optimal solution, because it only tries to pass as few intersections as possible. Depth-first search does much worse still: it keeps driving criss-cross through the city until it happens to end up at the goal, avoiding only the intersections it has already visited. For this delivery it covers more than 10 kilometers that way, against about 1 kilometer with uniform-cost search.

Loading demo

If you switch off "🏠 Goal" in the simulator above, it computes a whole tree of optimal paths from the pizzeria across all of Leuven. That way we could compute, for the pizzeria, a whole map of Leuven with the shortest paths to every intersection, so that the app only has to do the computation once. This variant is called "Dijkstra's algorithm", after the Dutch computer scientist Edsger Dijkstra (external link), who invented it. Drag the pizzeria to another location (for example your own student room) to find the optimal tree of shortest paths from there.

🧭 Heuristics

So far, the search algorithms assumed that they know nothing about where the goals are. Just like breadth-first search, uniform-cost search and Dijkstra's algorithm explore in all directions at once. As a result, they spend a lot of time searching in directions that you, as a human, can easily see are wasted effort.

But often you do know something useful. Think of your GPS: if your destination lies far to the east, there is no point in expanding all the paths to the west just as much. Can you give priority to states that are closer to the goal in a straight line, and so make the search algorithm smarter? Yes, with the help of a heuristic.

Heuristic Definition

A heuristic is a clever rule of thumb or an "educated guess" that gives a quick but imperfect estimate to help solve a problem.

In our case, a heuristic is an estimate of how far (in terms of path cost) a state still is from the goal. It is a way of telling the algorithm: "This path looks promising, give it priority!" We write this as h(n)h(n): the estimated cost from state nn to the goal.

🧳 Lost tourist Example

Imagine: you are a tourist, lost in a city, and your phone battery is dead. You want to get to the central station. You can use various heuristics to reach the station anyway:

  • 🔊 Sound: if you hear a train, you walk in that direction. The louder the sound, the closer you are.
  • 👀 Sight: you see the clock tower of the station rising above the surrounding buildings.
  • 🧳 Behavior: people with suitcases are probably on their way to the station. The more suitcases, the closer.
  • 🗺️ Geography: stations often lie low, so you choose streets that go downhill.

None of these rules of thumb is perfect, but together they will hopefully take you in the right direction.

A good heuristic steers the algorithm toward attractive states, but stays cheap to compute. Such a heuristic typically has three properties:

  1. 🎯 Informative: the closer to the solution, the lower the value h(n)h(n). Ideally that value is as close as possible to the actual remaining cost.
  2. ⚡ Fast: better a rough guess in milliseconds than perfect information that takes minutes.
  3. ✅ Admissible: for the A* algorithm (which comes up later in this chapter), h(n)h(n) has to be "optimistic": it never overestimates the actual cost to the goal. Equal is allowed, higher is not.
🛒 Supermarket checkout Example

When you have to choose a line at the supermarket checkout, you probably use a heuristic. Some people simply look at the number of people in each line and pick one of the shortest. But others apply a more informative heuristic and look, for example, at:

  • 🛒 Number of products per line: how many products all the customers in the line have in their shopping carts, to know how many items have to be scanned.
  • 👩‍💼 Cashier speed: whether the cashier is an experienced employee or a student worker, to estimate the scanning speed.

By roughly multiplying those two quick estimates, this more informative heuristic will probably save you, on average, just a little more time in line.

📏 Distance heuristics

For search problems with locations (such as the mazes and the Leuven pizzeria), you can make heuristic estimates based on distances. Which formula you use as the heuristic h(n)h(n) depends on how the location system works: can you move in any direction (Euclidean distance), or are you stuck on a grid with only horizontal and vertical moves (Manhattan distance)?

Two different kinds of distance measurement

Two different ways to measure distances between the points (2,1) and (6,4).

🕊️ Euclidean distance

For route planning, the most obvious heuristic is the straight-line distance, also called the Euclidean distance: the straight line from where you are to your destination. It never overestimates the real cost: the route along the streets is never shorter than the straight line, at most just as long.

You compute the Euclidean distance between two points with coordinates (x1,y1)(x_1, y_1) and (x2,y2)(x_2, y_2) with:

d=(x1−x2)2+(y1−y2)2d = \sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}

This formula is an application of the Pythagorean theorem: a2+b2=c2a^2 + b^2 = c^2. The straight line between the two points is the hypotenuse cc of a right triangle, whose other two sides are the horizontal difference a=x1−x2a = x_1 - x_2 and the vertical difference b=y1−y2b = y_1 - y_2. So you find the length of the straight line with c=a2+b2c = \sqrt{a^2 + b^2}.

For example: from (2,1)(2, 1) to (6,4)(6, 4) that distance is (2−6)2+(1−4)2=16+9=25=5\sqrt{(2-6)^2 + (1-4)^2} = \sqrt{16 + 9} = \sqrt{25} = 5.

🗽 Manhattan distance

For a grid such as the maze, you often use the Manhattan distance as the heuristic. This distance is the sum of the horizontal and vertical steps you need to take, at the very least, to get from one point to the other.

You compute the Manhattan distance between two states with coordinates (x1,y1)(x_1, y_1) and (x2,y2)(x_2, y_2) as:

d=∣x1−x2∣+∣y1−y2∣d = |x_1 - x_2| + |y_1 - y_2|

The vertical bars (∣…∣|\ldots|) stand for the absolute value: you keep positive numbers as they are and drop the minus sign of negative numbers. So ∣3∣=3|3| = 3 and ∣−3∣=3|-3| = 3. The absolute value of a difference, such as ∣x1−x2∣|x_1 - x_2|, therefore measures how far apart two numbers are, regardless of which number is larger.

To get from (2,1)(2, 1) to (6,4)(6, 4) you need at least three steps up and four steps to the right, so 77 steps. This matches the formula: ∣2−6∣+∣1−4∣=4+3=7|2-6| + |1-4| = 4 + 3 = 7.

This heuristic never overestimates the real distance: because in the maze you can only move horizontally and vertically, it is exactly right when there are no obstacles. The real path can be longer if there are obstacles in the way.

Why Manhattan? Did you know?

The name Manhattan distance comes from the grid pattern of the streets in Manhattan, New York. Between two intersections in the city there are often several paths that are all equally long, as long as you move toward your goal at every intersection: horizontally or vertically. However you navigate, you always take the same number of horizontal and vertical steps.

Map of Manhattan, which is one big grid

Map of Manhattan (OpenStreetMap (external link))

Suppose you are on a pub crawl through Leuven and have to walk from the 🚶 Oude Markt to 🦊 café De Reynaert. Which streets do you intuitively consider first? You probably choose the intersections that bring you closer to the goal in a straight line.

Now that you have heuristics, you can let search algorithms search with that kind of intuition too. This is what greedy search does. Greedy search keeps the paths in the frontier fully sorted by the heuristic value h(n)h(n). Here h(n)h(n) estimates how far the goal still is from the state at the end of the path, for example using the straight-line distance. Greedy search always prefers the state that, according to the heuristic, seems closest to the goal. Try it out below by clicking "Solve". Do you agree with this walking route?

Loading demo

You can see that greedy search follows the Naamsestraat a little too long, while it would have done better to take the Parkstraat. That is because the intersection with the Karmelietenberg simply lay closer to the goal than the intersection at the start of the Parkstraat. In the example above, set the search algorithm to "Uniform-cost search" and compare the paths: here uniform-cost search does find this shorter path, saving 300 meters compared to greedy search.

Unlike uniform-cost search, greedy search ignores the cost g(p)g(p) of the path pp already traveled and only looks at a rough estimate h(n)h(n) of the remaining cost from state nn. That is why it is called "greedy": it always dives into the most promising option, hoping to reach the goal quickly.

Below you see a maze world with a top view of two buildings. For greedy search we use the Manhattan distance as the heuristic here, because you can only move vertically and horizontally. We make use of the fact that the diamond (💎) of the goal state is at position (14,7). For each cell, the algorithm can then use the Manhattan distance to compute how far it is from that coordinate. This value is shown at the top of each cell and corresponds to how many steps you would have to take if there were no blocks in the way. The color shows it too: the brighter orange a cell, the lower h(n)h(n) and the closer it is to the goal according to the heuristic. If you drag the diamond, the values at all positions change too. Adding or removing walls (by dragging) does not change these values.

Loading demo

Also compare it with the path that uniform-cost search finds (or breadth-first search, as the two are the same here because every action costs the same). Notice that the path greedy search found is not an optimal path: it takes 30 steps, while the one uniform-cost search finds takes only 20. This is because greedy search always chose the cell with the lowest Manhattan distance. That lured it into the dead-end corner between the two buildings: close to the goal in a straight line, but with a wall in between. After that it still had to go all the way around along the top, while there was a shorter path that initially looked less promising. Greedy search did finish much sooner, though: after 40 search steps, while uniform-cost search needs 122.

Greedy search behaves like a focused version of depth-first search. It keeps going in the direction that looks best, unless it finds a better heuristic value somewhere else. If all expansions of the current state are worse than the best state in the frontier, it goes back to that better option.

So greedy search is fast, but not always optimal. It keeps pushing on in the direction with the best heuristic score, even if that path ends in a dead end.

Sometimes, besides giving priority to promising options, you also want to limit the size of the frontier, especially for problems with an enormous number of possibilities. Beam search does exactly this. In beam search you fix how large the frontier may become (the "beam width" kk): you keep only the kk best options in the frontier. This technique limits memory use and is useful for very large search spaces.

This is useful, for example, in language models that predict the next word. Instead of storing hundreds of thousands of possible words in the frontier, you keep only the most likely options and their expansions, or you randomly pick a few based on their predicted probabilities.

Search tree with three levels in which, each time, only the two states with the lowest heuristic value stay in the frontier and the others are thrown away.

Beam search with beam width k=2k = 2: after each expansion the algorithm keeps only the two best states and immediately throws away the rest.

⛰️ Variant: Hill climbing

An extreme case of beam search in a state space arises when the beam width is 1, so that no frontier is left: only the current best candidate. We call this hill climbing: you look at the neighboring states of the current state and step to the neighbor that gives the biggest improvement, without looking back. The algorithm cannot return to earlier choices and must always move forward.

The name "hill climbing" immediately suggests a handy analogy. Picture the search space as a landscape: every state is a spot, and how good that state is determines how high that spot lies. In hill climbing you step each time to the neighboring spot that lies highest, until no neighbor lies higher. That way you are guaranteed to end up on a peak, but not necessarily on the highest peak of the whole landscape.

Fifteen states as bars side by side, with a low peak on the left and a higher one on the right. Hill climbing starts on the left, steps each time to the highest neighbor and stays on the low peak, because both neighbors there are lower.

Hill climbing steps each time to the neighbor that lies highest, and stops as soon as both neighbors are lower. So it stays on the low peak on the left: to reach the higher peak on the right, it would first have to go down.

Such a peak, where every neighboring state is worse, is called a local optimum. Further on there may be a better state, but hill climbing then misses it. Greedy search does get out of such a local optimum: thanks to its frontier it goes back to an earlier path, as with the dead-end corner between the two buildings above.

Still, hill climbing is useful for optimization problems with an enormous search space, where keeping a frontier so that you can later go back to earlier choices (known as backtracking) is not practical, and where a "good" solution is enough. A scheduler that assigns tasks to machines can, for example, keep swapping two tasks between machines, as long as that makes the project finish sooner.

Later in the course you will come across the same idea in machine learning: gradient descent descends instead of climbing, and each time takes a small step in the direction in which the error of a model decreases fastest. Just like hill climbing, it never looks back, which is why a neural network can get stuck in a local minimum of the error.

In the previous sections you saw two algorithms that keep their frontier sorted in a clever way: uniform-cost search and greedy search. One finds paths with the lowest path cost, the other reaches a decent path to the goal faster. Both have their problems, though:

  • ⚖️ Uniform-cost search is guaranteed to find the path with the lowest cost in a search space with weighted actions, but it is slow because, just like breadth-first search, it spends a long time searching in all directions.
  • 🤤 Greedy search is fast because it searches in a targeted way, but just like depth-first search it can find suboptimal paths, because it keeps building on a path that is not optimal.

Can you combine speed and optimality? Yes, with the A* algorithm (pronounced "A-star")!

🧮 Sorting by f-value

In the A* algorithm, the frontier stays sorted by a so-called f-value. For a path in the frontier that ends in state nn, it is:

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

Where:

  • g(n)g(n) = the actual path cost from the start to state nn: the path cost g(p)g(p) of that path pp, as in uniform-cost search
  • h(n)h(n) = the heuristic estimate of how far state nn still is from a goal state (as in greedy search)
  • f(n)f(n) = the estimated total cost of the cheapest path to the goal via state nn

This way, f(n)f(n) balances the distance already traveled against the estimate of what remains. By combining both, A* takes into account both "how far you have already come" and "how far you probably still have to go".

If the heuristic never overestimates the remaining cost, like the straight-line distance on a map, then f(n)f(n) is an underestimate of the cost of the best path via nn: the real cost is at least as high. As a result, A* is guaranteed to find the cheapest path. You can read exactly why further on, in Underestimating heuristics.

🗽 Manhattan heuristic

Try it yourself below in a few grid worlds (where the heuristic is the Manhattan distance) and compare the paths of greedy search with those of A*. Uniform-cost search and A* always find paths with the same path cost, but A* usually gets there faster. Test this by making your own worlds with variable costs: with the brush button ( Wall) you choose whether you draw a wall, water or grass. Then click or drag over the cells to create them or remove them again.

Loading demo

🕊️ Euclidean heuristic

With the A* algorithm you can find, very efficiently, paths that are guaranteed to have the lowest cost. That is why your GPS also uses this kind of algorithm to suggest the best routes for your car trips in no time. You can often choose whether the "cost" should be time or distance; that determines which cost you assign to the actions between the intersections.

Below you can try out A* and all the other algorithms discussed on the map of Leuven. Can you position the start and goal states so that greedy search falls into the trap, while A* finds a much shorter path?

Loading demo

Notice how the three algorithms behave:

  • ⚖️ Uniform-cost search spreads out like an oil slick: it explores the cheapest streets first, regardless of direction.
  • 🤤 Greedy search immediately forces a path in the straight-line direction of the goal, even if that eventually makes it take a detour.
  • 🌟 A* combines both: it mostly heads in the straight-line direction, but in the end finds the same optimal path as uniform-cost search.

⬇️ Underestimating heuristics

A* needs one important condition to guarantee optimality: the heuristic has to be admissible. A heuristic h(n)h(n) is admissible when it never overestimates, that is, when it never estimates higher than the actual shortest distance from nn to the goal. In other words: h(n)≤h∗(n)h(n) \le h^*(n), where h∗(n)h^*(n) is the real remaining cost. So an equal estimate is allowed, a higher one is not.

❓ Why does this matter for A*?

For a path in the frontier that ends in state nn, f(n)=g(n)+h(n)f(n) = g(n) + h(n): the cost g(n)g(n) already paid plus an underestimate h(n)h(n) of what is still to come. As a result, f(n)f(n) is never larger than the actual cost of the cheapest solution that continues that path. So when A* takes a path to a goal state out of the frontier, we know that this path is the cheapest: every other path in the frontier has an ff-value that is at least as large, and so cannot end up cheaper.

We can prove this as follows:

  1. For every path in the frontier that ends in state nn, f(n)=g(n)+h(n)f(n) = g(n) + h(n) with h(n)≤h∗(n)h(n) \le h^*(n) (the real remaining cost).
  2. Therefore f(n)≤g(n)+h∗(n)f(n) \le g(n) + h^*(n): f(n)f(n) underestimates the total cost of every solution that continues this path.
  3. Now look at the end of the algorithm, when A* takes a path to a goal state GG out of the frontier. Because h(G)=0h(G) = 0, f(G)=g(G)f(G) = g(G): the real cost of that solution.
  4. A* always takes the path with the lowest ff-value out of the frontier, so at that moment every other path in the frontier has f(n)≥f(G)f(n) \ge f(G). Every other solution builds on one of those paths and, by step 2, costs at least f(n)f(n), so at least g(G)g(G): there is no cheaper solution.

What happens if the heuristic is not underestimating (and so sometimes overestimates)? Then A* loses its guarantee of optimality: a path with too high an h(n)h(n) wrongly looks too expensive and stays at the back of the frontier, so A* can pick a suboptimal path as its final solution.

🎚️ Try under- and overestimating

To try this out, you use a heuristic weight below: the heuristic is the Manhattan distance multiplied by that weight. That way you choose yourself how optimistically or pessimistically A* looks at the remaining distance.

  • Weight 0: the heuristic says h(n)=0h(n) = 0 everywhere. A* then becomes uniform-cost search: guaranteed to find the cheapest path, but slow.
  • Weight between 0 and 1: the heuristic underestimates. A* stays optimal and gets faster as the weight increases.
  • Weight greater than 1: the heuristic overestimates. A* finishes even sooner, but the path it finds is no longer always the cheapest.

In the world below, a wide river lies between 🙂 and 💎. Straight through the water is by far the shortest route in number of steps, but every water cell costs 10, so that crossing costs 44 in total. Walking around the river takes more steps, but they cost only 1 each: 28 in total. The Manhattan distance does not see that difference, because it only counts steps and knows nothing about water.

Slide the weight up and watch two things at once: how many iterations A* needs, and the label under the slider that says whether the path it found really is the cheapest.

  • With weight 1, A* needs 77 iterations and finds the detour with cost 28.
  • From about weight 3 on, A* is done after only 43 iterations, but it wades through the river and pays 44: almost 60% more expensive.

The detour starts with steps away from the goal. As soon as you inflate the heuristic enough, A* sees those first steps as hopeless and no longer looks at them. You can see the same thing happen in the frontier: with a higher weight, the paths that go through the river move up, while the detour sinks to the back.

Loading demo

Also use the maze selector to pick a different maze: in some worlds A* still finds the cheapest path even with weight 5. So overestimating does not always go wrong. What you lose is the guarantee: afterwards you no longer know whether the path you got was the best one, and that is exactly what the condition of admissible heuristics gave you.

In practice, engineers nevertheless often choose such an inflated heuristic on purpose, because a good path that is ready quickly can be worth more than the best path that comes too late. You are not left entirely without a guarantee then: if the heuristic without the weight is admissible, the path that A* finds with weight ww costs at most ww times as much (external link) as the cheapest path. With weight 3 above, the crossing costs 44, well below 3×28=843 \times 28 = 84. Robots can therefore first search for a path quickly with a high weight, so that they can set off right away, and then lower the weight step by step to improve the path as long as there is time.

📈 The need for good heuristics

🏅 The quality of your heuristic

The performance of heuristic algorithms depends heavily on the quality of the heuristic:

  • If h(n)=0h(n) = 0 for all states, the heuristic gives no information. A* then behaves exactly like uniform-cost search.
  • If h(n)h(n) estimates the actual distance perfectly, A* finds the optimal path without any unnecessary exploration.
  • If h(n)h(n) overestimates the distance, A* loses its guarantee of optimality and may return a path that is not the shortest one.
🧩 Sliding puzzle heuristics Example

A sliding puzzle consists of eight numbered tiles and one empty cell in a three-by-three grid. Each move slides a tile that lies next to the empty cell into that cell, until all tiles are in order. As a search problem, every arrangement of the tiles is a state and every slide is an action with cost 1.

To solve such a puzzle with A*, you need a heuristic that estimates how many more moves are needed. The same problem often has several possible heuristics. Two classic choices:

  • 🔢 Number of misplaced tiles, also called the Hamming distance: count how many tiles are not yet in their goal position. Every such tile has to be moved at least once more, so this heuristic never overestimates.
  • 🗽 Sum of the Manhattan distances: for every tile, count how many steps (horizontal plus vertical) it takes to bring it to its goal position, and add up those distances. This never overestimates either: every move shifts one tile by one cell, so every tile needs at least as many moves as its Manhattan distance.
On the left the start state 8 7 3, 2 6 4, blank 1 5, on the right the goal state 1 2 3, 4 5 6, 7 8 blank. Seven tiles are misplaced; their Manhattan distances add up to 16. The shortest solution takes 20 moves.

Only tile 3 is already in place. The number in the corner of each tile is its Manhattan distance to its goal position.

In the puzzle above, seven tiles are misplaced, so the first heuristic estimates that at least 7 more moves are needed. The second adds up the Manhattan distances and estimates 16. The shortest solution takes 20 moves: so both heuristics underestimate, and with either of them A* is guaranteed to find that shortest solution.

Still, they are not equally good. A tile that lies three cells away from its place, like tile 8, counts for 1 in the first heuristic and for 3 in the second. The sum of the Manhattan distances is therefore never lower and usually higher than the number of misplaced tiles, so it lies closer to the real number of remaining moves. It is more informative: for this puzzle, A* explores some 150 to 200 states with it before it finds the shortest solution, while with the number of misplaced tiles it needs more than ten times as many states.

🧰 Which algorithm should you choose?

The three algorithms in this chapter differ only in the value by which they sort their frontier: uniform-cost search by the path cost g(n)g(n), greedy search by the heuristic h(n)h(n), and A* by the sum f(n)=g(n)+h(n)f(n) = g(n) + h(n). That makes the choice between the three simple:

  • 🌟 A* is almost always the best choice: it is guaranteed to find the cheapest path and explores far fewer states to do so than uniform-cost search. You do need to find a good heuristic for it, one that never overestimates the remaining cost.
  • ⚖️ Uniform-cost search is what remains if you cannot find such a heuristic. It is really A* with h(n)=0h(n) = 0.
  • 🤤 Greedy search is useful when you have little time to compute a path, and what matters most is to find a path quickly, even if it is not the best one. Take a sliding puzzle of four by four cells: for a well-shuffled puzzle, A* often explores more than a million states before it finds the shortest solution, while greedy search usually has a solution after a few thousand states (although it often takes two to four times as many moves). If you just want to see the puzzle solved, you will be happy with that. In computer games too, where many characters need a route at the same time, you usually do not really need the best path, as long as the game does not stutter.
Property⚖️ Uniform-cost search🤤 Greedy search🌟 A*
🔀 Frontier sorted byg(n)g(n): the path cost so farh(n)h(n): the estimated remaining costf(n)=g(n)+h(n)f(n) = g(n) + h(n)
📏 Optimality✅ Guaranteed to find the cheapest path.❌ Can take long detours.✅ As long as the heuristic never overestimates.
♾️ Completeness✅ Always finds a solution if one exists.⚠️ Only in a finite search space.✅ Like uniform-cost search.
⌚ TimeHigh: explores in all directions.Low: heads straight for the goal.Lower as the heuristic gets more informative.
📝 MemoryHigh: the frontier spreads like an oil slick.Low: the frontier stays narrow.High with a weak heuristic, lower with a good one.

🏭 Heuristic search in practice

Heuristic search is not just for mazes, maps and puzzles. As soon as you can describe a problem with states, actions that have a cost, and an estimate of the remaining cost, you can solve it with A*. A few examples:

  • 🔌 Designing circuit boards and chips: the electrical connections between the components must not touch each other. A routing program lays them out one by one on a fine grid, and for every new connection it looks for a short path around the connections that are already there: a maze like the ones in this chapter. The classic Lee algorithm (external link) from 1961 did this with breadth-first search; modern routing programs use A* for it (external link).
  • 📅 Scheduling: which task do you run on which machine, and in which order, so that the whole project is finished as soon as possible? A state is then a partial schedule, and an action schedules one more task. A heuristic that never overestimates is, for example, the longest chain of tasks that still have to happen one after the other: even with infinitely many machines, the project cannot be finished any sooner than that.
  • 🔧 Fault diagnosis: a device does not work, and every test of a component costs time or money. In which order do you test the components to find the defect as cheaply as possible? A state is what you already know after the previous tests, and a heuristic estimates how much the remaining testing will cost at the very least. With such an admissible heuristic, a variant of A* is guaranteed to find the test order that costs the least on average.

🧪 Hands-on

So far, you have seen the A* algorithm at work in demos. Now you apply it yourself with real Python code, in a Jupyter notebook: a document in which explanation alternates with short pieces of code. You run that code for free in Google Colab, right in your browser. Never programmed before? No problem: start with the short introductory notebook, a gentle introduction to Python and notebooks. The A* notebook below then guides you step by step, and each time you only change a few small pieces of code.

An implementation of A*, applied to a word ladder and to a real route between two places on OpenStreetMap.

🕹️ Demos

🗣️ Feedback

Just like machine learning algorithms, we also love learning from your feedback to improve the course.

Let us know how informative and how difficult you found this chapter, and where it could be better.

How informative did you find this chapter?
Was the difficulty of this chapter right for your level of knowledge and skill? This chapter was...
Anonymous with random ID