Loading
Breadth-first search explores a graph level by level with a queue; depth-first search goes as deep as it can with a stack, then backs up. Both visit every reachable node once.
Search the graph with edges A–B, A–C, B–D, B–E, C–F, E–F, D–G from A, by breadth-first and by depth-first search (neighbours in alphabetical order).
Visit the front of the queue, then add its unvisited neighbours to the back.
| Step | Visit | Added to queue | Queue (front first) |
|---|---|---|---|
| 1 | A | B, C | B, C |
| 2 | B | D, E | C, D, E |
| 3 | C | F | D, E, F |
| 4 | D | G | E, F, G |
| 5 | E | — | F, G |
| 6 | F | — | G |
| 7 | G | — | — |
Go as deep as possible along the first unvisited neighbour; back up when stuck.
| Step | Visit | Still to explore | Stack (top first) |
|---|---|---|---|
| 1 | A | B, C | A |
| 2 | B | D, E | B, A |
| 3 | D | G | D, B, A |
| 4 | G | — (back up) | G, D, B, A |
| 5 | E | F | E, B, A |
| 6 | F | C | F, E, B, A |
| 7 | C | — (back up) | C, F, E, B, A |
The calculator below opens on this example.
Visiting a node twice.
Using a stack for BFS.
Ignoring the neighbour order.
Shortest paths with weights.
Neighbours are visited in alphabetical (or numerical) order.
Add this calculator to a new note, next to your own working. It stays live: change the numbers there any time.