Walking a graph

BFS and DFS, now with cycles · Part of Trees and graphs

Key idea

Practice

6 questions · about 3 min

Explained step by step

Breadth-first search (BFS)

BFS on a graph starts at a vertex and first visits all its neighbors, then those neighbors' neighbors, and so on, like a ripple. It uses a queue: the starting vertex is enqueued; each round one is dequeued, marked visited, and its not-yet-visited neighbors are enqueued. Since a tree is a special case of a graph, it's the same level-order walk, with one extra care: no repeats.

Unlike a tree, a graph can have cycles: paths that return to the same vertex, like 1-2-3-1. Without care, a traversal would go around forever. That's why a visited set is kept, a hash table with the vertices already seen. Before enqueueing or visiting a vertex, you check whether it's there: in O(1).

Both traversals cost O(|V| + |E|) in time: each vertex is visited once, and in an undirected graph each edge is looked at twice, once from each end. In memory, both are O(|V|): the visited set and the result hold up to |V| vertices, so does the BFS queue, and the DFS recursion can reach |V| levels.

Graph traversals solve very different problems. BFS is for the shortest path in number of steps, like degrees of separation between 2 people, or for finding everything k steps away. DFS is for exploring everything reachable, detecting cycles, or solving mazes and puzzles by trying paths. Both work for checking whether a graph is connected.

Depth-first search (DFS)

DFS on a graph follows a path as far as it can: from the current vertex it goes to an unvisited neighbor, and from there to another, until none is left unvisited. Then it backtracks to the last vertex with pending neighbors and tries another path. It's naturally written with recursion, and also uses a visited set to avoid repeats.

A traversal's order isn't unique: it depends on the order in which each vertex's neighbors are checked. If 1 has neighbors 2 and 3, a BFS can visit 1, 2, 3 or 1, 3, 2, and both are correct. What is guaranteed is the shape: BFS finishes each layer before the next, and DFS finishes each path before backtracking.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

BFS and DFS, now with cycles