🔍 Search Algorithms
This chapter opens the part on reasoning: AI systems that typically do not learn from examples, but compute a solution themselves for a problem you have described exactly. That is the symbolic AI the field started with. It gets its name because such systems reason with symbols: names that a human can read and that each stand for something concrete, such as an intersection, a chess piece or the statement "it is raining". The simplest way to reason like this is search: systematically trying out possibilities until you find a solution. Your GPS does this to compute a route, a puzzle program to solve a sudoku, and planning software to draw up optimal schedules. This chapter covers the basic search algorithms, heuristic search makes them smarter, game trees add an opponent, and logic reasons with rules instead of actions.
📚 Types of search algorithms
Can you solve the maze below? Drag a path from the smiley to the diamond.
How did you go about it?
- Did you first try to trace out one path until you could go no further, and then return to an earlier fork?
- Did you look ahead at every junction to the possible paths that followed from it?
- Did you start from the end, and work your way back to the beginning?
- Did you systematically try out every possible path? Or did you prefer paths that went right or down, because you knew the diamond was there?
- How sure are you that you found the shortest path?
There are clearly different strategies (= search algorithms) to solve the maze. It is not so easy to say which strategy is the "best" one for any maze.
A search algorithm is a strategy for finding a solution to a problem step by step, by systematically exploring possible options.
Ideally, a search algorithm finds a sequence of actions that leads to a solution. We call this a found path from a start state to an end state.
A sequence of actions in a search problem, starting from the start state of that problem.
In the maze above, for example, every sequence of steps you take from the smiley is a path, such as "go down, go down, go right, …".
There are different types of search algorithms, each with its own approach, advantages and disadvantages. In this chapter we discuss basic search algorithms (depth-first search and breadth-first search) that work on search spaces with the following properties:
- Unweighted: every action costs the same amount of "effort", like the steps in the maze above.
- Uninformed: no information is available beforehand about where a goal state lies in the search space.
In the next chapter on heuristic search we look at search algorithms that work with weighted actions (so with different costs) and where we do have information about the goal state.
🕳️ Depth-first search
Depth-first search is a search algorithm that searches as far as possible in one direction before it goes back and tries other paths. In the maze below, click Solve, or step through the search one step at a time with the arrow buttons at the top.
If a path hits a dead end, depth-first search goes back to the last fork where it can still try another way. We call this backtracking. To know which ways are still open, it keeps track of the paths that are still waiting for their turn: the frontier. In the simulator you see it as the cells with a blue dotted line: each of those cells is the end of a path that is still waiting. The cell with the orange border and the number 1 is the first to get its turn.
Depth-first search always tries the directions in a fixed order: in our simulator the default is up first, then right, then down and then left. At every decision point it applies the same rule:
- Go through the directions in that order and take the first one that works: not into a wall and not to a cell that has already been visited.
- No direction works? Then this path is a dead end, and you go back (backtracking) to the previous decision point, where you continue with the next direction you had not tried there yet.
The light purple and dark purple cells have already been visited (dark purple is the path the algorithm is following now), and it does not step onto them again. A cell that is still waiting in the frontier does not count as visited yet: if the algorithm passes it by another route, it simply steps onto it.
This way depth-first search quickly finds a solution, but not necessarily the shortest one. With the default order it finds a path of 56 steps via the right side here, while the shortest path (44 steps) runs through the lower left part, which the algorithm never explores.
There are two things you can change in the simulator yourself:
- The order of actions: with the settings button next to the name of the algorithm you choose a different order. If you let the algorithm try down first, for example, it happens to find the shortest path here after all.
- 🧱 The maze: click a cell (or drag across cells) to place or remove a wall, and see how the path found changes.
🌳 Breadth-first search
Breadth-first search is a search algorithm that explores all possible paths of a given length before it moves on to longer paths. Try it in the same maze:
Breadth-first search first explores all cells that can be reached directly from the start cell, then all cells two steps away, and so on. So it searches the search space in "layers" of equal distance from the start state.
Because it works so systematically, breadth-first search, unlike depth-first search, does always find the shortest path to the goal, here the one of 44 steps. That comes at a price, though: it visits more cells before it finds the diamond (compare the purple cells with those of depth-first search).
🧩 Defining a search problem
To solve a problem with a search algorithm (and so find a path), you first translate it into an abstract form that a computer understands: states, and actions that take you from one state to another. For that you need four elements:
- A state definition: what a state is, so what the system looks like at a given moment.
In the maze: a position on the grid, as an (x,y) coordinate. - A start state: the state where the search begins.
In the maze: the place of the 🙂 smiley, (1,1). - A transition function: which actions you can take from a state, and which new states you then end up in. We call those new states expansions of the path.
In the maze: a step left, right, up or down, as long as you do not walk into a wall. - A goal test: a criterion that says whether a state is a solution.
In the maze: is there a 💎 diamond on the cell?
You can apply this to other search problems too.
Problem setting: A 👨🌾 farmer arrives at a river. He wants to bring his 🦊 fox, 🐔 chicken and 🌾 grain safely to the other side in a small 🛶 boat that only holds the 👨🌾 farmer + one passenger.
Rules: The following rules apply in this problem:
- If you leave the 🦊 fox and the 🐔 chicken together without the 👨🌾 farmer, the 🦊 fox eats the 🐔 chicken.
- If you leave the 🐔 chicken and the 🌾 grain together without the 👨🌾 farmer, the 🐔 chicken eats the 🌾 grain.
- The 👨🌾 farmer must always steer the 🛶 boat himself; the 🛶 boat cannot cross on its own.
You can formulate this as a search problem, as explained above:
-
State definition: who is on which bank. In the notation below the river 🌊 lies in the middle and ◻️ is an empty place:
👨🌾🦊🐔🌾 🌊 ◻️◻️◻️◻️ means: everyone is on the left of the river
◻️🦊◻️🌾 🌊 👨🌾◻️🐔◻️ means: fox and grain are on the left, the farmer and the chicken are already on the right of the riverA state that breaks one of the two rules is invalid. You choose the notation yourself: FoG|FaC (fox and grain on the left, farmer and chicken on the right) works just as well.
-
Start state: 👨🌾🦊🐔🌾 🌊 ◻️◻️◻️◻️ (everyone is on the left bank)
-
Transition function: from every state the farmer can
- cross to the other side alone, or
- cross to the other side together with the 🦊 fox, the 🐔 chicken or the 🌾 grain.
Only a crossing that ends in a valid state produces an expansion.
Example expansion:
👨🌾🦊🐔🌾 🌊 ◻️◻️◻️◻️
→ ◻️🦊◻️🌾 🌊 👨🌾◻️🐔◻️ (the farmer takes the chicken along)
→ 👨🌾🦊◻️🌾 🌊 ◻️◻️🐔◻️ (the farmer crosses back alone) -
Goal test: everyone is on the right bank: ◻️◻️◻️◻️ 🌊 👨🌾🦊🐔🌾.
Exercise: Now solve this manually by choosing actions yourself. Do it once the way depth-first search would (follow one path as far as possible, and only go back when you get stuck) and once the way breadth-first search would (first look at all states after one crossing, then all states after two crossings, and so on). Each time, skip the states you have already come across. Which states does each algorithm visit?
⚙️ The search process
🧠 Memory elements
Search algorithms typically use a few memory elements to support their work. Depth-first and breadth-first search both use a frontier to keep track of which paths they still have to explore further, and they also keep track of which cells they have already visited:
-
Frontier: the frontier contains all paths that the algorithm will still try to extend in order to find a solution. Every path in the frontier is an extension of a path that the algorithm explored earlier.
-
Visited states (optional): these are the states that the algorithm has visited before, so states for which a path has already been found.
Keeping track of visited states (or cells, in our maze) is often a smart choice. In the implementation of depth-first and breadth-first search that we use in the earlier examples, every cell is visited at most once. That makes the algorithm more efficient: you only need to keep one path per cell, and you prevent the algorithm from returning to a cell it has visited before.
Sometimes, though, you do not want a cell to be visited only once, for example when the first path found to that cell is not the best one.
➡️ The search process step by step
With these memory elements, a search algorithm builds up paths step by step from the start state. At the beginning the frontier contains only the start state, which for the maze is the location of the smiley. In each following step the algorithm takes the first path out of the frontier and extends it with all possible actions from the last state of that path. New paths that lead to an already visited state are thrown away immediately. It repeats this until a path in the frontier passes the goal test. Usually that means reaching a goal state such as the diamond, but it can also be a more complex test, such as checking whether a king is checkmated in chess.
If a new path leads to a state for which a path is already waiting in the frontier, the two algorithms deal with it differently. Breadth-first search throws the new path away: the waiting path is at least as short. Depth-first search simply puts the new path at the front of the frontier, and skips the older path when its turn comes later.
In the simulator below you can see the current step and watch the frontier evolve over time, for the two algorithms from before.
- Step through the iterations manually, and for every step try to predict what will happen in the next one:
- Which state will be explored next?
- Which new paths will be added to the frontier?
- Click and drag with your mouse across the maze to turn a wall into a passage (and the other way around), and predict what effect this change has on the path.
- Do the exercises above for both depth-first and breadth-first search.
Tips for the simulator above:
- Fullscreen: Click "Fullscreen" to get a clearer view.
- 👣 View a path: Move your mouse over (or tap) an item in the frontier or in the list of neighbors to see which path it represents.
- Expansion order: Click the settings next to the algorithm selector to change the order of actions (for example trying down first instead of up). See how the path differs for depth-first search.
- Reset maze: This button appears at the top right of the maze as soon as you have changed the maze, and puts the original maze back.
🔁 Dealing with repeated states
Keeping track of visited states is only one way to tackle a fundamental problem: in most search spaces you can reach the same state via different paths. In the maze, for example, you reach a cell via a short and a long route, or even just by stepping back and forth. Without countermeasures the frontier fills up with such repeated states: the algorithm then wastes time on parts of the search space it already knew, and can even keep going around in a loop forever. There are three classic strategies to deal with this:
-
Remember all visited states: keep a visited set and reject every expansion to a state that is already in it. That way every state is visited at most once. This is what the maze simulator does (the purple cells). For breadth-first search you also lose nothing by doing this: the first path by which you reach a state is right away the shortest path to that state. The price is memory: the set grows with the number of visited states.
-
Only avoid loops in the current path: only check whether the new state already occurs in the current path (cycle checking). This costs almost no extra memory and prevents a path from going around in circles endlessly. Different paths may still lead to the same state, though, so the algorithm can do a lot of duplicate work. This strategy is useful when memory is limited, or when the first path found to a state is not necessarily the best one and you therefore want to be able to look at that state several times.
-
Make repetition impossible through your problem definition: sometimes you can formulate the search problem so that every state can be reached via only one path, so that repeated states simply do not exist. Suppose you treat putting together the ideal burrito as a search problem, with "add an ingredient" as the action. If every ingredient may be added at any moment, you reach the burrito with cheese and beans in two ways: first cheese and then beans, or the other way around. If, on the other hand, you impose a fixed order in which the ingredients have to be added, there is only one path to each burrito and your algorithm does not need to keep track of anything extra.
Which strategy is best depends on the search problem: it is a trade-off between extra memory (strategy 1), possible duplicate work (strategy 2) and how much freedom your problem definition allows (strategy 3).
🕸️ Graph representation
To represent a search problem on a computer, you usually use a graph: a set of nodes (the circles in the figure below), some of which are connected by an edge (the arrows).
A search problem as a graph, at some moment during the search. Each circle is a state and each arrow an action. The blue states have already been visited, the yellow ones are in the frontier and the gray ones have not been explored yet. (based on Poole & Mackworth (external link))
Such a graph is used in two ways for a search problem:
- States as nodes: the search space. Every possible state is represented as one node, and every action is an edge between two states. For example: in the maze every free cell is a node, with an edge to every cell adjacent to it. Solving a search problem then means looking for a path from the start node to a goal node. In the previous maze simulator you can visualize that graph with the button at the bottom left.
- Paths as nodes: the search tree. In the frontier, a search algorithm does not keep track of separate states but of paths up to a certain state. Every action extends a path into a longer path. You can visualize this step to a longer path with a graph as well, by drawing an edge to a node that represents the longer path. That way you get a search tree like the one in the image above.
You notice the difference with a state that you can reach by several routes. In the fox, chicken and grain problem, the farmer can take the 🦊 fox across first and the 🌾 grain later, or the other way around: in both cases he ends up in the same state, with only the 🐔 chicken still on the left bank. In the search space that is one node. In the search tree it is two, because they are two different paths. If the algorithm remembers which states it has already visited, it throws that second path away immediately.
In the simulator above you can look at both representations yourself: at the bottom left, switch from Maze to Graph. Every free cell then becomes a node, and every passage between two cells an edge: that is the search space. When you let the algorithm run, the edges it follows become arrows. Together those arrows form the search tree, with the nodes in the frontier (the blue dotted line) as its ends. For the Tower of Hanoi further on, you see the search tree grow separately below the towers.
A search algorithm sees only this graph, without knowing what the states really stand for in the real world. It works purely with abstract states, actions and paths. That is why it is important to make a good abstraction of your search problem, one that you can translate into this abstract form.
Graphs and trees come back often in this course, among others in game trees, decision trees, Bayesian networks and neural networks.
🛠️ Implementing search algorithms
Want to program a search algorithm yourself? You actually do not need much code for that. Everything you saw in this chapter (the frontier, the visited states, expanding and the goal test) fits together in one short loop. What is more, this template works for every problem that you define as a search problem: only the start state, the transition function and the goal test differ from problem to problem.
function search(search_problem): frontier = [path with only the start state] visited = empty set while frontier is not empty: path = take the first path out of frontier state = last state of path if state is in visited: continue with the next path # another path got here earlier add state to visited if goal_test(state) succeeds: return path # 🎉 solution found! for each neighbor of state: if neighbor is not in visited: add path + neighbor to frontier # at the front or at the back? return "no solution found" # frontier is empty: everything searchedThis loop follows the search process step by step exactly as described earlier:
- 🏁 Start: the frontier contains one path: the start state itself, without any actions yet.
- 🔁 Each round: take the first path out of the frontier. If its last state has meanwhile been visited via another path, you skip it. Otherwise you mark that state as visited and run the goal test. If it succeeds, this path is the solution and you are done.
- 🌱 Expanding: if not, use the transition function to generate all neighboring states, reject the states that have already been visited, and add the extended paths to the frontier.
- 🚫 No solution: if the frontier runs empty, every reachable state has been explored and no solution exists.
Notice something in the pseudocode above: nowhere does it say which search algorithm this is. Depth-first and breadth-first search differ in only one line, namely the highlighted line where you add new paths to the frontier.
- If you add new paths at the front, the frontier behaves like a stack: the path added last is the first to be extended again ("last in, first out"). So the algorithm keeps making the newest path longer, and automatically falls back on an older path when that one hits a dead end. That is exactly the behavior of depth-first search, backtracking included.
- If you add new paths at the back, the frontier is a queue: paths get their turn in the order in which they were added ("first in, first out"). That way all paths of length get their turn before the paths of length : that gives breadth-first search, which searches layer by layer. A new path to a state for which a path is already waiting in the frontier always gets its turn after that waiting path here, and is then skipped. So you might just as well throw it away right away, as the simulator does.
And it goes further: replace the frontier with a priority queue that always puts the path with the lowest (expected) cost at the front, and you get the smarter algorithms from the next chapter, such as uniform-cost search and A*. So the code above is a template in which one adjustable line can stand for a whole family of search algorithms.
🦍 The brute force of basic search algorithms
Sometimes the two basic algorithms look dumb: look, for example, at how much work the breadth-first algorithm below seems to waste by searching in directions that are of no use. But depth-first search also makes big detours in this world.
This is because these two algorithms are uninformed: they have no idea where the goal state lies in the search space. In their standard form, depth-first and breadth-first search really use "brute force" to navigate through the search space.
People often make clever choices on the spot, or use their experience and intuition to solve problems. One possible way to add a little of that kind of intuition after all is to use depth-first search with a preferred order of actions. Change the order of actions in the simulator above to a preference for right and down, and see how this affects the path that depth-first search finds.
In the next chapter on heuristic search we look at how you can give search algorithms that kind of intuition after all, with the help of heuristics.
Another example of a search problem is the classic game of the Tower of Hanoi. This game consists of a board with three rods and disks of different diameters with a hole in the middle. On each rod, a disk may only lie on top of a larger disk.
At the start all disks are on the left rod. The goal is to move the entire tower of disks to another rod, with the following rules:
- you may move only 1 disk at a time
- you may never place a larger disk on a smaller disk.
Try to solve it yourself manually, with three disks, in the simulator below:
You can cast this puzzle in the same four elements of a search problem: a state is the distribution of the disks over the rods (for example [1,2,3],[],[] as the start state), the transition function moves the top disk of a rod to a rod that is empty or has a larger disk on top, and the goal test checks whether all disks are together on a rod other than the one they started on.
When you solved the problem manually, you may quickly have discovered a pattern that always gets you to a solution efficiently, even with many disks. Uninformed search algorithms such as breadth-first and depth-first search, however, have a hard time when there are many disks. They do not look for such a pattern, but blindly apply their search strategy step by step, and so try to reach a solution by brute force.
Look at the search tree below the towers, and at how the states are searched for each algorithm, in the simulator below:
You see a clear difference between the paths found with breadth-first and depth-first search: a longer path with depth-first search, and a longer search with breadth-first search. This difference grows even bigger with more disks and towers. Try the following in the simulator below, which has more towers and disks:
-
Click " Solve": normally you will find a path of 13 steps that solves this puzzle with breadth-first search.
-
Click the " Reset" button to reset the puzzle to the start state.
-
Look at the search tree visualization below the towers, select "Depth-first search" and click " Start" and then to go to the last step (or go back to the start position and press " Solve").
-
Depth-first search now shows a path of more than 200 steps. While breadth-first search always finds the shortest path, depth-first search, just like a human, keeps building on previous states, even if it made a mistake along the way.
Loading demo
But even breadth-first search struggles with many disks. The number of actions in the shortest solution grows exponentially with the number of disks. Try setting the simulator above to 7 disks and then letting breadth-first search solve it.
In the classic version with 3 rods you need 3 actions for 2 disks, 7 for 3 disks, 15 for 4 disks, 31 for 5 disks, 63 for 6 disks and 127 actions for 7 disks. In general, for disks and 3 rods you need at least actions (external link). So that grows very fast!
🌳 Depth-first search vs breadth-first search
In this chapter we saw two different algorithms: depth-first search and breadth-first search. The difference between them lies simply in where they add new paths to the frontier, which leads to completely different behavior:
- Depth-first search adds new paths at the front of the frontier. As a result it immediately tries to keep building on the previous path, and goes back to an earlier choice point when it gets stuck.
- Breadth-first search adds new paths at the back of the frontier. As a result it always looks at the paths of a given length before it moves on to longer paths.
This difference gives the two search algorithms different properties in the following areas:
- 📏 Optimality: the length of the path found
- ♾️ Completeness: whether they ever find a solution when one exists
- ⌚ Time: guarantees on how many states they have to visit before they find a solution
- 📝 Space: how much computer memory they require
🌿 Solution length and branching factor
Two important concepts for talking about these differences are the optimal solution length and the branching factor of a search problem.
The solution length is the length of the shortest path from the start state to a goal state.
The branching factor of a search problem is the number of actions that are possible in each state. If this varies from state to state, you can compute the average branching factor.
For example:
- Maze: For our maze the branching factor is typically about 3, because in each state (cell) you can take at most 4 actions (left, right, up, down), but only in the start state can you actually perform all 4 actions.
- Tower of Hanoi: For the Tower of Hanoi with 3 towers the branching factor is about 3. In each state you can in theory take 6 actions: move the top disk of one of the three rods to one of the two other rods. Typically at least half of these actions are not valid, because you would then place a disk on a smaller disk, or because the chosen rod is empty.
📏 Optimality: length of the path found
As we saw earlier, depth-first search does not necessarily find the shortest path. Breadth-first search, on the other hand, does guarantee that the path it finds is the shortest.
This is clearly visible in the maze below. Breadth-first search finds a path of length 6, while depth-first search finds a path of length 22. However you change the order of expansions in depth-first search with the button, it will never find the shortest path.
The following holds:
-
Breadth-first search is optimal: You can prove formally that breadth-first search always finds the shortest path. It visits all paths of length before it starts on paths of length . The first path found to a given state (the goal state included) is therefore by definition the shortest one to that state. Consequently, the algorithm finds the shortest path, of length , to the nearest goal state.
-
Depth-first search is not optimal: This algorithm can take a much longer route, because it simply follows the first available path. So there is no guarantee that the path it finds is the shortest.
♾️ Completeness: guarantee of finding a solution
In a finite search space (such as our maze and the Tower of Hanoi), both algorithms always find a solution path in finite time, although that time can be long. But what about infinite search spaces, such as a maze on an infinite grid?
Take a simple example with an infinite space:
- State definition: an integer
- Start state: 0
- Transition function: from state you can go to state or
- Goal state: -1
In this infinite search space you see the difference in completeness between the algorithms:
- Breadth-first search visits two states after the start state 0: first 1 and then -1. It stops after this step, because it has reached the goal state -1.
- Depth-first search, on the other hand, first visits 1, then 2, then 3, and so on. So it will never reach the goal state -1, and keeps searching forever. It is therefore not a complete search algorithm: it does not guarantee that it ever finds a solution, even when one is reachable.
So the following holds:
- Breadth-first search is complete: This algorithm expands systematically, layer by layer, through the search space until it comes across a solution. If there is a solution that requires actions, it cannot get lost on an infinitely long path: it finds the solution before it would look at the paths of length . So it always finds a solution if one is reachable, and is therefore a complete search algorithm.
- Depth-first search is not complete: As shown above, in an infinite search space this algorithm can keep descending into one branch forever without ever coming back. Think of an infinitely large maze in which it would just keep walking down.
⌚ Time to find a solution
How many states does the algorithm have to explore before it finds a solution? The more states it visits, the longer the algorithm will have to search.
- Because breadth-first search is complete, you can compute from the nearest goal state how many states it has to visit at most.
- Depth-first search follows a path rather arbitrarily, so it can sometimes be faster, but sometimes also much slower.
An important property that can cause a difference in time is the number of goal states. If there are many different goal states, depth-first search can sometimes find a path faster than breadth-first search. After all, it does not have to look at all paths of length before it looks at paths of length , as in the maze below. In this case it looks at only 4 states, against 14 for breadth-first search.
-
Depth-first search: Because it goes "deep" so quickly, it keeps drilling down along one path and sometimes finds a solution with far fewer visited states than breadth-first search. Breadth-first search, after all, also explores semi-irrelevant choices (such as which empty rod you put the top disk on when there are several options) in parallel, and the number of those parallel paths doubles with every such choice. So depth-first search is a gamble: it is just as likely to get lost in deep (or even infinite) paths and take much longer instead.
-
Breadth-first search: This algorithm can guarantee that it finds a solution within a fixed number of steps. The maximum number of states it has to look at for that does grow exponentially with the solution length , on the order of .
🔢 How many states does breadth-first search examine at most?
If you know that the solution requires actions and that you can take at most actions in each state, then you can show that breadth-first search looks at a number of states on the order of in the worst case. It systematically looks at every path of length before it starts on length . Because of the branching factor , it has to visit about times more states at each depth. So it looks at states before it finds a solution. For that sum stays below , which is a finite number.
For example: in the maze we know that there are at most four actions per state (up, down, left, right). If there is a path of length 10, breadth-first search visits all paths with lengths 1 to 10. There are at most 4 paths of length 1, paths of length 2, of length 3, and so on up to of length 10. If you add up all these paths, you can show mathematically that the total is always lower than .
📝 How much computer memory is needed?
Depth-first and breadth-first search differ strongly in memory use in their standard version, where they only keep a frontier and do not keep track of which states they have already visited.
- Depth-first search: This algorithm only keeps the current path, plus the paths still open at earlier steps, in the frontier. Because there are at most actions in each state, each step adds at most new paths to the frontier, so the frontier contains at most paths, where is the length of the first path in the frontier. The number of paths in the frontier also shrinks again when the algorithm goes back to a previous state.
- Breadth-first search: At the end, this algorithm has exponentially more states in the frontier, namely on the order of , where is the depth of the solution. In the worst case there can be that many paths of length , after all. Because of this, breadth-first search is sometimes not feasible for enormous search spaces: the computer memory fills up completely with possible states. In chess, for example, there are roughly 35 possible moves (external link) per turn. To compute chess positions 10 moves deep, there are possible chessboards, a number with 16 digits! That is why, for problems like these, it is often not possible to search more than a few moves deep with breadth-first search.
🧭 Which algorithm should you choose when?
Both basic search algorithms are powerful: in many cases they guarantee that you find a solution without needing clever hints about the goal states. But there are also limitations to consider when you choose. An overview:
-
Depth-first search is ideal for a large, tree-shaped search space with few or no loops, and when the length of the path matters less. For certain puzzles its backtracking behavior is a perfect fit: in a Sudoku you try a possibility, and if it does not work you go back to try the next one. For the same reason, depth-first search is relevant to large AI domains such as logic, constraint satisfaction problems and other tree-like search spaces such as game trees.
-
Breadth-first search is ideal when finding the shortest path matters, as in navigation and planning problems, or when you suspect that the goal lies relatively close to the start. In a social network, for example, it finds how far away from you someone is: a second- or third-degree connection on LinkedIn is someone in the second or third layer of a breadth-first search from your profile.
The exact guarantees of both algorithms are summarized in the table below. Modern AI systems use clever trade-offs or entirely different algorithms to get around these limitations, but the core ideas of breadth-first and depth-first search remain important for understanding how algorithmic search works.
| Property | Depth-first search | Breadth-first search |
|---|---|---|
| 📏 Optimality | No guarantee; can make big detours. | Guaranteed to find a shortest path (if all costs are equal). |
| ♾️ Completeness | Not complete in infinite or cyclic graphs without cycle checking. | Complete: will always find a solution if one exists. |
| ⌚ Time | No guarantee: often faster than breadth-first search when there are many goals or when the solutions lie deep, but sometimes also much slower. | Exponential in the path length : on the order of . |
| 📝 Memory | On the order of : linear in the depth of the current path. | On the order of : keeps all paths of length . |
🕹️ Demos
Experiment further with the full simulators and demos featured above.
🗣️ 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.

