BFS and DFS on a graph

Video lessonComing soon

1 A graph can lead back to where we started

The graphs lesson drew a small city of seven junctions. Now we want to explore it. Which junctions can we reach from junction 0, and how many roads away is each one?

0123456
The city. Junctions 5 and 6 sit on an island

A tree walk goes from a node to its children, and it never meets a node twice. A graph's roads go both ways: 1 lists 0 as a neighbour, just as 0 lists 1. So the tree walk, copied as it is, goes from 0 to 1, from 1 back to 0, and on forever:

walk(0)walk(1)walk(0)walk(1)walk(0)top →
The calls pile up until the stack overflows

The call stack overflows, and the program stops with a Runtime Error.

An explorer in a maze avoids this with chalk. They mark each junction the first time they reach it, and never walk into a marked one again. In code, the chalk is an array visited, with one place per vertex. Each vertex is then handled once, so the walk ends.

With the chalk, there are two ways to explore:

  • Breadth-first search (BFS) spreads like ripples from a stone dropped at 0: every junction one road away, then two roads away, and so on.
  • Depth-first search (DFS) walks like the explorer. It follows one road as far as it goes, then steps back and tries the next.

2 BFS: ripples from junction 0

BFS uses the queue from the level order lesson, plus the chalk. It also gives each vertex its distance dist, the number of roads from the start:

  1. Mark 0, set dist[0] to 0, and put 0 in the queue.
  2. Take the vertex u at the front of the queue.
  3. For each neighbour v of u that is not marked: mark v, set dist[v] to dist[u] + 1, and add v at the back.
  4. Go back to step 2 until the queue is empty.

The neighbours come from the adjacency list, adj:

1, 200, 2, 311, 021, 43346556
adj: box u lists the neighbours of u

In the steps, filled vertices are marked, and the purple one is being taken. The number by each vertex is its dist, and ? means not reached yet. Bold roads found a new vertex. In the queue, crossed boxes have been taken, and orange ones were just added.

BFS from junction 0
001?2?3?4?5?6?
001234
Start: mark 0, dist 0, queue it

The same run as a table:

TakenIts neighboursNewly markedQueue after
01, 21 and 2, dist 11, 2
10, 2, 33, dist 22, 3
21, 0none3
31, 44, dist 34
43noneempty

The queue handed out the vertices in order of distance: 0, then 1 and 2, then 3, then 4. Those are the ripples. The answer is dist = [0, 1, 1, 2, 3, -1, -1]. The code keeps -1 for the ?, since 5 and 6 cannot be reached.

3 Mark a vertex when it joins the queue

Step 3 marks v when it joins the queue, not later when it is taken. Vertex 2 shows why. Here is the loop with the mark moved to the moment of taking:

take u from the front
if u is marked: skip it
mark u
add every neighbour of u that is not marked

Taking 0 adds 1 and 2. Taking 1 then looks at 2. Vertex 2 is waiting in the queue but not marked yet, so it joins a second time:

001122233445
Marking late: 2 joins the queue twice

Here it costs one extra entry. In a dense graph, a vertex joins once for each neighbour taken before it. With 1,000 vertices all joined to each other, the queue gets about 5 × 10⁵ entries instead of 1,000, about one per edge. Marking on joining keeps each vertex in the queue at most once.

4 Why BFS finds the fewest roads

The ripples show why dist holds the fewest roads. A vertex at distance d + 1 is found from a vertex at distance d. The queue hands out every vertex at distance d first, because they all joined earlier. So the first vertex to reach v is one of the nearest, and the mark stops a later, longer route from changing dist[v].

This needs every road to count the same. In the graphs lesson, the drive 0, 2, 1 was 3 km, shorter than the direct road of 4 km, but it takes two roads. BFS counts roads, not kilometres. Weighted graphs need Dijkstra's algorithm, in a later lesson.

To rebuild the route itself, we store parent[v] = u when u finds v. These links are the bold roads in the last BFS step. From 4 we walk back to 3, then 1, then 0. Reversed, the route is 0, 1, 3, 4.

00112132435?6?
Following parent links back from 4 gives 4, 3, 1, 0

The code returns dist. A value of -1 means not seen yet, so dist also does the job of visited:

C++

front, then pop. pop() removes the front but returns nothing, so we read the vertex with front() first.

ArrayDeque as the queue. offer adds at the back and poll takes from the front, both in O(1).

deque, not a list. popleft() takes from the front in O(1). A list's pop(0) shifts every value left, so it is O(n).

An array with a front index. shift() moves every value, so it is O(n). Reading pending[front] and adding 1 to front is O(1).

A slice as the queue. pending[1:] drops the front without copying anything, so each take is O(1).

VecDeque as the queue. pop_front returns an Option, so while let stops the loop when the queue is empty. Vertices are usize, because they index dist.

Queue<T>. Enqueue adds at the back and Dequeue takes from the front, both in O(1).

Cost. Each vertex joins the queue once, and its row of adj is read once. The rows hold 2E entries, one for each end of each road. So BFS takes O(V + E) time, around 5 × 10⁵ steps at V = 10⁵ and E = 2 × 10⁵. The dist array and the queue take O(V) space.

With an adjacency matrix, each vertex's row has V entries to read. That makes BFS O(V²): 10¹⁰ steps at V = 10⁵, which gets TLE.

5 DFS: follow one road to the end

The explorer does not spread out. They take the first road to an unmarked junction and carry on from there. At a dead end, where every neighbour is marked, they step back one junction and try its next road. Recursion does exactly this. Each call stands at one junction, and returning is the step back:

dfs(u):
    mark u
    for each neighbour v of u:
        if v is not marked: dfs(v)

The call stack holds the route from 0 to where the explorer stands, like a thread unwound behind them. In the steps, the purple vertex is where they stand:

DFS from junction 0
0123456
dfs(0)top →
dfs(0): mark 0, go on to 1

DFS reached 2 by two roads, 0, 1, 2, although 2 sits next to 0. DFS reaches every vertex it can, but not by the shortest routes.

The same walk runs with a stack of our own, as in the iterative traversals lesson:

push 0
while the stack is not empty:
    pop u
    if u is marked: skip it
    mark u
    push unmarked neighbours, last first

The neighbours go in last first, so the first comes out first, and this visits 0, 1, 2, 3, 4 as the recursion did. The mark comes when a vertex is popped, so a vertex can sit in the stack twice. Marking on push visits 0, 1, 3, 4, 2 instead. It still reaches everything, but the order is no longer depth-first.

Deep graphs. On a chain of 10⁵ vertices, recursive DFS goes 10⁵ calls deep. The call stack is much smaller than the rest of memory, so it can overflow with a Runtime Error. Then use BFS or the explicit stack.

The two searches side by side:

BFSDFS
OrderNearest first, ripple by rippleOne road to its end, then back
KeepsA queueThe call stack, or a stack
Fewest roadsYes, when every road counts 1No
Extra memoryThe widest ripple, up to O(V)The current route, up to O(V)
Typical usesDistances, fewest stepsReaching everything, components, all paths

6 Every piece of the map

BFS from 0 left 5 and 6 at -1. A traversal reaches only the connected component it starts in. To visit the whole graph, or count its pieces, we try every vertex as a start and skip the marked ones. Each unmarked start is a new component.

0123456
Two components: the mainland and the island

On our city:

startMarked already?What happenscount
0noDFS marks 0, 1, 2, 3, 41
1 to 4yesskipped1
5noDFS marks 5, 62
6yesskipped2

On our city it returns 2. Each vertex is still marked once and each row read once, so the whole loop is O(V + E). BFS in place of dfs gives the same count.

7 Grids are graphs too

Many problems give a grid instead of edges: land and water, or fresh and rotten oranges. Each cell is a vertex. Its neighbours are the cells above, below, left and right, so we work them out as we go instead of building adj.

01234567891011
Cell 5 has four neighbours
01234567891011
Corner cell 0 has only two

A cell at the edge has fewer neighbours, so each of the four moves is checked against the grid's bounds before the cell is read:

directions = (-1, 0), (1, 0), (0, -1), (0, 1)
for each (dr, dc) in directions:
    nr = r + dr
    nc = c + dc
    if 0 <= nr < rows and 0 <= nc < cols:
        (nr, nc) is a neighbour of (r, c)

visited becomes a 2D array the size of the grid, or the grid itself is changed, say by turning visited land into water. A grid of R rows and C columns has R × C vertices and at most 4 roads at each, so a traversal is O(R × C).

Many starts at once. Sometimes the spread starts from several cells together, as when every rotten orange spoils its neighbours each minute. We put all the starts in the queue with distance 0 before the loop, then run BFS as usual. The ripples grow together, and each cell's dist is its distance to the nearest start. This is multi-source BFS.

012212212210
Two starts. Each cell holds its distance to the nearer one

8 Mistakes, and when to use them

  • Marking when taking. On our city, 2 joins the queue twice. On a dense graph the queue grows to about one entry per edge, and the run can get TLE or run out of memory.
  • Starting from one vertex only. BFS from 0 never reaches 5 and 6. A question about the whole graph needs the loop over every start.
  • Leaving the grid. From corner cell 0, the move up reaches row −1. Without the bounds check, reading it is a Runtime Error, or a wrong value with no error at all.
  • One visited for many test cases. If one input holds several graphs and visited is made once, the second graph starts with the first one's marks. Make a fresh visited for each graph.

The sign is a graph, given as edges or neighbours, and a question about which vertices we can reach:

  • Can we reach it? Mark everything reachable from the start, with BFS or DFS, and check the marks.
  • The fewest steps, when every step costs the same. BFS, reading dist.
  • How many pieces? The loop over every start.
  • Every route from a to b. DFS that writes down the route as it goes deeper, and removes the last vertex as it steps back.

The next lesson uses DFS to ask whether a walk can come back to where it started: cycle detection.

Before writing a traversal, decide when a vertex gets its mark. In BFS, mark it when it joins the queue. In DFS, mark it when its call starts, or when it is popped.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.