Graph search: breadth-first and depth-first
A subway map, a friend network, links between web pages and a maze are all "points with lines between them". There are two ways to start at one point and visit every place you can reach. Press "Next" and follow them one step at a time.
Short answer. Breadth-first search (BFS) visits the closest nodes first and spreads out like a ripple. Depth-first search (DFS) follows one path as far as it goes, then backs up. The code differs in one line. Take the next node from a queue (oldest first) and you get breadth-first. Take it from a stack (newest first) and you get depth-first. Both take time in proportion to the number of nodes plus the number of edges, and when every edge has the same length, BFS finds the shortest path.
Orange is the node just taken out (the "now" arrow). Green nodes are visited (the number in the black circle is the visit order). Blue dashed nodes wait in the queue or stack. Gray nodes are not seen yet. A thick green edge is the edge a node was first reached by, and it stays as the steps go on. Each node is shown in three steps: take out → look at the neighbors → put in. In the look step, a thick blue "in" arrow points to a neighbor that is not visited yet and will go in, and a faint gray "visited" arrow points to a neighbor that is already visited and will not. The row of boxes at the bottom of the picture is the queue or stack, and the orange box comes out next. A queue takes items in on the right (back) and gives them out on the left (front). A stack takes items in and gives them out at one end only, the right end (top). The arrow on the side where something happened in that step turns thick. Switch the method in the middle to see the other method at the same step.
Definitions
The text below explains in plain words. These are the textbook definitions. V is the set of nodes and E is the set of edges. When we write running time, V and E also stand for how many there are (the O(V + E) in the text).
- graph
- A pair of a set of nodes V and a set of edges E. In an undirected graph an edge is an unordered pair {u, v} of nodes. In a directed graph it is an ordered pair (u, v). If the edge {u, v} exists, u and v are adjacent (they are neighbors).
- adjacency list
- A way to store a graph that keeps, for each node v, the list Adj[v] of the nodes adjacent to v. In an undirected graph the edge {u, v} appears once in Adj[u] and once in Adj[v], so the lengths of all the lists add up to twice the number of edges.
- path, shortest path
- A path of length k from u to u′ is a sequence of nodes with and in which every two neighbors in the sequence are joined by an edge. In a graph without weights, the length of a path is the number of edges k it uses. A shortest path from s to v is such a path with the smallest length, and that length is the shortest distance from s to v.
- breadth-first search (BFS)
- A graph search that starts at a node s and visits every node at shortest distance k from s before any node at distance k + 1. It puts the nodes to visit in a queue (first in, first out, FIFO) and takes them from the front. In a graph without weights it finds a shortest path from s to every node it can reach. With an adjacency list it takes this time:
- depth-first search (DFS)
- A graph search that goes deeper from the most recently visited node while that node still has a neighbor that has not been visited, and goes back to the node it came from when there is none. It puts the nodes to visit on a stack (last in, first out, LIFO) and takes them from the top, or it uses recursive calls. With an adjacency list it takes O(V + E) time, the same as BFS.
1. What a graph is: nodes and edges
A graph is made of nodes (points) and edges (lines that join two nodes). Stations and the tracks between them, people and friendships, web pages and links are all graphs. Two nodes joined directly by an edge are neighbors.
The graph in the demo has 9 nodes (A to I) and 10 edges. The edges have no direction, so the edge A–B takes you from A to B and from B to A. There is also a cycle, a path that comes back to where it started (B → D → G → E → B). Because of cycles, a search has to remember where it has been (section 5).
2. How to store it: adjacency lists
The most common way to store a graph is an adjacency list: for each node, keep a list of its neighbors. In Python, one dict does the job.
graph = {"A": ["B", "C"], "B": ["A", "D", "E"], "C": ["A", "F"],
"D": ["B", "G"], "E": ["B", "G", "H"], "F": ["C", "H"],
"G": ["D", "E"], "H": ["E", "F", "I"], "I": ["H"]}
One edge (A–B) is written twice: as B in the list of A, and as A in the list of B. So all the lists together are twice as long as the number of edges, 20 here. This page lists neighbors in name order. Change the order of a list and the visit order changes too. You can also use a table with one cell for every pair of nodes (an adjacency matrix), but with V nodes that is V × V cells, and for a graph with few edges most of them are empty.
3. One difference: where the next node comes from
Both methods hold one to-do list and repeat the same moves.
- Put the start node in the to-do list.
- Take one node out of the list.
- If it was already visited, throw it away and go back to 2.
- If it is new, mark it as visited and put all its neighbors that are not visited yet into the list.
- Repeat 2 to 4 until the list is empty.
Only step 2 is different.
- Breadth-first: a queue. The oldest item comes out first, like a line at a shop. You finish every node 1 edge away from the start before you move on to nodes 2 edges away. That is why it spreads like a ripple.
- Depth-first: a stack. The newest item comes out first, like a pile of plates. You go straight into the neighbor you just added, and only when there is nowhere left to go do you come back to a branch you left earlier.
Try this. ① With breadth-first, keep pressing "Next". The visit order is A, B, C, D, E, F, G, H, I. It visits B and C (1 edge from the start) before D, E, F (2 edges), then G, H, and I last. ② Switch to depth-first at the same step. The order is A, C, F, H, I, E, G, D, B. The stack gives back C first because C went in last, so the search goes all the way down the C side. B went in first and is visited last. ③ In breadth-first, step 21 takes out G and step 25 takes out H, and both are thrown away at once. Two neighbors each put the same node in. ④ The queue is at most 4 long (steps 15 and 18). The stack is at most 3 long. ⑤ In breadth-first, following the thick green edges from the start gives the path with the fewest edges to every node. In depth-first it does not: the path from A to B goes around 7 edges.
4. Trace it by hand
Here is the same graph as the demo, from A to the end. One row is one take-out of a node (the demo splits it into up to three steps: take out → look at the neighbors → put in). A circled number is the visit order, and the "after" columns show the list after the neighbors went in. For the queue, the left end is the front (comes out next). For the stack, the right end is the top (comes out next). The last column says why that node came out.
| Take-out | Breadth-first: taken out | Queue after | Depth-first: taken out | Stack after | Why that node |
|---|---|---|---|---|---|
| 0 | (put in A) | A | (put in A) | A | start by putting in the start node |
| 1 | A ① | B C | A ① | B C | A is the only item in both |
| 2 | B ② | C D E | C ② | B F | queue front B (in first) · stack top C (in last) |
| 3 | C ③ | D E F | F ③ | B H | queue front C · stack top F (just put in) |
| 4 | D ④ | E F G | H ④ | B E I | queue front D · stack top H (just put in) |
| 5 | E ⑤ | F G G H | I ⑤ | B E | queue front E · stack top I (in after E) |
| 6 | F ⑥ | G G H H | E ⑥ | B B G | queue front F · stack top E (uncovered when I left) |
| 7 | G ⑦ | G H H | G ⑦ | B B D | queue front G · stack top G (just put in) |
| 8 | G thrown away | H H | D ⑧ | B B B | queue: G already visited at ⑦ · stack top D (just put in) |
| 9 | H ⑧ | H I | B ⑨ | B B | queue front H · stack top B (put in by D) |
| 10 | H thrown away | I | B thrown away | B | queue: H already visited at ⑧ · stack: B already visited at ⑨ |
| 11 | I ⑨ | (empty) | B thrown away | (empty) | queue front I · stack: B already visited at ⑨ |
Look at take-out 4 of depth-first. H comes out and its neighbors E and I go in. I went in last, so it sits on top and comes out next. In breadth-first, I would wait at the back of the queue and come out after G and H.
5. Without the visited mark, it never stops
Remove "if it was already visited, throw it away" from section 3. A comes out and B goes in. B comes out and its neighbor A goes in again. A comes out and B goes in again. The search bounces across one edge forever, and the to-do list never empties. With a cycle (B → D → G → E → B), it goes round and round. So you keep a visited mark. In Python that is a set. If your nodes are numbered, it is a true/false array with one slot per node.
On this page both methods mark a node when it comes out. That way the two programs differ only in the line that takes a node out. The cost is that the same node can be in the list twice (the G G at take-out 5 in section 4). For breadth-first you can mark a node when it goes in instead. The visit order stays the same and no node enters the queue twice, so that is how it is usually written.
6. In a maze: the shortest path
A grid maze is a graph too. Each cell is a node, and the open cells directly above, below, left and right are its neighbors. The search starts at the top left and stops when it takes out the goal at the bottom right. Each cell remembers which cell it was reached from, so following those notes back from the goal gives the path that was found.
The big number in the middle of a cell is how many moves from the start along the path the search used to get there. The small number at the bottom right is the visit order of that cell. Green cells are visited, blue dashed cells are waiting, the orange border is the cell just taken out, and dark cells are walls. Blue arrows point from the current cell to the neighbor cells it put into the to-do list. "Next" goes on until one new cell is visited (steps that only throw away an already visited cell are skipped). Neighbors go in the order up, right, down, left. The walls come from a random number generator with a fixed seed, so the maze is the same every time you open the page.
Try this. ① With breadth-first, keep pressing "Next". The numbers spread 1, 2, 3 and so on like a ripple. Every cell with one number is visited before any cell with the next number. ② Press "To the end": the path has length 14 and 47 cells were visited. 14 is 7 moves right plus 7 moves down, so no path in this grid can be shorter. ③ Switch to depth-first and press "To the end": the path has length 28 and 30 cells were visited. Fewer cells, but a path twice as long. Depth-first hands back the first path it reaches and never checks whether it is the shortest. ④ Look at the third row, second column. When depth-first finishes it shows 17. When breadth-first finishes it shows 3. A depth-first number is not the shortest distance. It is the length of the winding path the search came in by.
7. How long it takes
time ∝ V + E (in books: O(V + E))
V: the number of nodes. Each node is marked once and its neighbor list is read once.E: the number of edges. All neighbor lists together have 2E entries, so looking at neighbors happens 2E times in total.∝: "is proportional to". Double the nodes and the edges, and the time roughly doubles.O( ): a notation that keeps only how fast the time grows as the input grows (time complexity).
Each edge puts a node into the list at most twice (once from each end), so counting every put and every take still gives something proportional to V + E. In the demo graph (V = 9, E = 10), both methods put 11 times and take 11 times. If you store the graph as a V × V table instead of lists, each node has to scan a whole row of V cells, so the time grows like V × V.
8. When to use which
| Method | Time (best · typical · worst) | Extra memory | Good | Bad | Use it for |
|---|---|---|---|---|---|
| Breadth-first (queue) | A few steps if the target is right next to the start · V + E to cover everything · V + E (double the nodes and edges, double the time) | V visited marks + the queue. All nodes at the same distance from the start sit in the queue together, so a wide graph makes a long queue | Finds the path with the fewest edges. Looks at close things first | Even when the target is far, it first looks at everything closer | Shortest paths when every edge has the same length (mazes, "how many steps apart") |
| Depth-first (stack or recursion) | Same | V visited marks + the stack. The stack holds the path you are on plus the branches you left beside it | Short to write (a few lines of recursion). Following one path to the end fits finding cycles and putting tasks in order | No promise that the path it finds is the shortest. Written with recursion, a very long path can make the calls go too deep | Exploring everything (is it connected, splitting into pieces), finding cycles, putting tasks in order |
If you mark nodes when they come out, as this page does, the same node can go in several times, and the queue or stack can grow in proportion to the number of edges. When edges have different lengths (time, distance, price), a path with fewer edges can still be longer. Then use Dijkstra's algorithm instead of breadth-first.
9. In Python
from collections import deque
def search(graph, start, wide=True):
todo, visited, order = deque([start]), set(), []
while todo:
node = todo.popleft() if wide else todo.pop() # queue: front, stack: back
if node in visited:
continue
visited.add(node)
order.append(node)
todo.extend(n for n in graph[node] if n not in visited)
return order
print(search(graph, "A")) # ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
print(search(graph, "A", wide=False)) # ['A', 'C', 'F', 'H', 'I', 'E', 'G', 'D', 'B']
graph is the dict from section 2. collections.deque is a list that is fast to add to and remove from at both ends. popleft() takes from the front (a queue) and pop() takes from the back (a stack). If you build a queue from a plain list and call pop(0), every remaining item has to shift over by one, so it gets slower as the list gets longer.
Where it is used
- Paths in mazes and game grids. When every move costs the same, breadth-first finds the shortest path.
- How many steps apart. In a graph of people, breadth-first counts the edges between two people.
- Is it connected, and splitting into pieces. Every node you reach from one node is one piece. Start again from a node you did not reach to find the next piece. Either method works.
- Finding cycles. In a graph without directions, if the search finds an edge to a visited node that is not the node it just came from, there is a cycle.
- Putting tasks in order. When edges have a direction, like "finish A before B", run depth-first and read the order in which nodes are finished backwards. That gives an order that works (build steps, course prerequisites). If there is a cycle, no such order exists.
Frequently asked
Do BFS and DFS visit different nodes?
No. Both visit every node you can reach from the start, each exactly once. Only the order is different. Nodes you cannot reach from the start are visited by neither.
Do I have to write DFS with recursion?
No. Recursion uses the call stack that the computer keeps for you, so using a stack yourself also gives depth-first search. The demo and the Python code on this page use a stack directly. With recursion you go into the first neighbor in the list first. With a stack you go into the last one first, so the order can differ, but both are depth-first.
Does BFS always find the shortest path?
Only when every edge has the same length. BFS finds the path with the fewest edges. When edges have different lengths or costs, a path with fewer edges can still be longer, so you use Dijkstra's algorithm instead.
Words
| Word on this page | Also called |
|---|---|
| node | vertex |
| edge | link, arc (when it has a direction) |
| neighbor | adjacent vertex |
| adjacency list | neighbor list |
| table of all node pairs | adjacency matrix |
| breadth-first | breadth-first search, BFS |
| depth-first | depth-first search, DFS |
| queue (oldest out first) | FIFO, first in first out |
| stack (newest out first) | LIFO, last in first out |
| list with two open ends | deque, double-ended queue |
| cycle | loop, circuit |
| visited mark | marked[] array, visited set |
| one connected piece | connected component |
| putting tasks in order | topological sort |
| shortest path | shortest path (fewest edges when edges have no length) |
Sources
- Robert Sedgewick, Kevin Wayne, Algorithms, 4th ed., 4.1 Undirected Graphs. Graphs and adjacency lists, depth-first and breadth-first search, time V + E, shortest paths with breadth-first search.
- Python documentation: collections.deque. Appends and pops at both ends, and why pop(0) on a list is slow.