Depth-first search, as deep as possible
After this: Follow depth-first search with its stack, and say why its order differs from breadth-first search.
On this page · 7 sections · 4 checks
Breadth-first search spreads outwards in layers. There is a second way to walk through a graph, and it is the way you would explore a maze on foot. You follow one corridor as far as it goes. At a dead end, you go back to the last place where you had another choice, and you try that.
This walk is called , or DFS. "Depth" means how far the walk has gone along one path.
The four friends, step by step
The rule has two parts. Move to the first neighbour that has not been visited. If there is none, back up to the node you came from.
To back up, the walk has to remember its path. A stack does this. A stack works like a pile of plates: you add to the top (push) and take from the top (pop), so the newest entry leaves first. The lesson on stacks explains more.
Here is the walk from Asha, with neighbours in alphabetical order. The stack holds the path from the start to the current node.
| Step | What happens | Stack after this step, bottom first |
|---|---|---|
| 1 | Visit Asha. | Asha |
| 2 | Ben is Asha's first unvisited neighbour. Visit Ben. | Asha, Ben |
| 3 | Ben's neighbour Asha is visited, and Dev is not. Visit Dev. | Asha, Ben, Dev |
| 4 | Dev's neighbour Ben is visited, and Cara is not. Visit Cara. | Asha, Ben, Dev, Cara |
| 5 | Cara's neighbours are both visited. Back up to Dev. | Asha, Ben, Dev |
| 6 | Dev has no unvisited neighbours left. Back up to Ben. | Asha, Ben |
| 7 | Ben has none left. Back up to Asha. | Asha |
| 8 | Asha has none left. Back up and stop. | empty |
The visit order is Asha, Ben, Dev, Cara. Breadth-first search gave Asha, Ben, Cara, Dev.
The code
Recursion gives us this stack without extra work. The computer keeps each unfinished call on the call stack, and the record of one call is called a frame. So we use one call for each node. Going deeper is a call, and backing up is a return.
def dfs(adj, node, visited, order): visited.add(node) order.append(node) # visit it for nb in adj[node]: if nb not in visited: dfs(adj, nb, visited, order) # go deeper; the call stack remembers the way back
order = []dfs(adj, "A", set(), order)print(order)['A', 'B', 'D', 'C', 'E', 'F']
static void dfs(Map<String, List<String>> adj, String node, Set<String> visited, List<String> order) { visited.add(node); order.add(node); // visit it for (String nb : adj.get(node)) { if (!visited.contains(nb)) dfs(adj, nb, visited, order); // go deeper; the call stack remembers the way back }}[A, B, D, C, E, F]
visitedandorderare shared by every call.orderrecords the visits.- Each call marks its node as visited and adds it to
order. - The loop calls the function again for each neighbour that has not been visited.
- When the loop ends, the function returns, and the call below carries on with its own loop.
On the six-node graph, C has no unvisited neighbours, so its call returns, and D goes on to E and then F. When F is visited, the call stack holds A, B, D, E and F. C is not there, because its call has already returned.
The same walk with a stack you can see
You can also create the stack yourself, using a lista deque. This matters for very big graphs, as the note at the end of this lesson explains. Here the stack holds the nodes waiting for their turn, not the path. Two details keep the visit order the same.
- Neighbours are pushed in reverse order, so the alphabetically first one ends up on top.
- A node is marked as visited when it is popped, not when it is pushed. So a node can be on the stack twice, and the second pop skips it.
def dfs_stack(adj, start): visited = set() order = [] stack = [start] while stack: node = stack.pop() # the top: the newest entry if node in visited: continue # pushed twice; an earlier pop already visited it visited.add(node) order.append(node) for nb in reversed(adj[node]): # reversed, so the alphabetically first is on top if nb not in visited: stack.append(nb) return order
print(dfs_stack(adj, "A"))['A', 'B', 'D', 'C', 'E', 'F']
static List<String> dfsStack(Map<String, List<String>> adj, String start) { Set<String> visited = new HashSet<>(); List<String> order = new ArrayList<>(); Deque<String> stack = new ArrayDeque<>(); stack.push(start); while (!stack.isEmpty()) { String node = stack.pop(); // the top: the newest entry if (visited.contains(node)) continue; // pushed twice; an earlier pop already visited it visited.add(node); order.add(node); List<String> ns = adj.get(node); for (int i = ns.size() - 1; i >= 0; i--) { // reversed, so the alphabetically first is on top if (!visited.contains(ns.get(i))) stack.push(ns.get(i)); } } return order;}[A, B, D, C, E, F]
Here is this version on the four friends. Step 3 puts Cara on the stack a second time, and step 5 skips her.
| Step | Pop | What happens | Stack after this step, bottom first |
|---|---|---|---|
| Start | nothing | Push Asha. | Asha |
| 1 | Asha | Visit Asha. Push Cara, then Ben. | Cara, Ben |
| 2 | Ben | Visit Ben. Push only Dev, because Asha is visited. | Cara, Dev |
| 3 | Dev | Visit Dev. Push only Cara, because Ben is visited. | Cara, Cara |
| 4 | Cara | Visit Cara. Push nothing. | Cara |
| 5 | Cara | She is already visited, so skip her. | empty |
One change makes the difference
Both walks keep some nodes waiting for their turn. Those nodes are called the . The walks differ in which one goes next.
| Breadth-first search | Depth-first search | |
|---|---|---|
| Waiting nodes are kept in | a queue | a stack |
| The next node is | the oldest one | the newest one |
| The walk moves | outwards, one layer at a time | as far as it can along one path |
| Order on the six-node graph | A B C D E F | A B D C E F |
After visiting B, breadth-first search goes to C, which has been waiting longer. Depth-first search goes to D, which is newer.
Watch it happen
Run DFS and then BFS from A, and compare the order strips. The DFS run asks for a prediction first: tap the node you expect to be visited third.
- DFS from ARun depth-first search from A. Follow the stack strip. It grows as the walk goes deeper, and it shrinks each time the walk backs up. The walk backs up to D before it reaches E.
- BFS from A
Pick a start node and run an algorithm.
Check yourself
DFS from A on the six-node graph has visited A, B and D. Which node is visited next?
DFS from A on the six-node graph, with neighbours taken in alphabetical order. In which order are the nodes visited?
In the recursive DFS from A, what is on the call stack at the moment F is visited? Read it from bottom to top.
The graph, the start and the neighbour order are the same. Why does BFS visit C third, while DFS visits it fourth?
Connect
- Follow depth-first search step by step, and say what is on the stack at any point.
- Write depth-first search with a stack you create yourself, and keep the recursive order.
- Explain why the two walks differ on the same graph: one takes the oldest waiting node, and the other takes the newest.