Module 20 of 39

Graph traversal: BFS, DFS, and topological order

Represent connections, traverse them, order dependencies, and find strongly connected groups.

A graph is a set of vertices joined by edges. Vertices can be people, places, files, or tasks. Edges say which pairs are related. A road may connect two places in both directions; a task dependency points one way. That distinction changes what questions we can ask.

Background for this page. A graph has vertices, which represent things, and edges, which represent connections. A path follows edges. A queue removes the earliest-added item; a stack removes the latest-added item. Related explanations: Arrays, linked lists, stacks, and queues · Single-source shortest paths: Dijkstra and Bellman–Ford.

An adjacency list stores each vertex’s neighbors. It is economical when there are relatively few edges. An adjacency matrix uses a row and column for every possible pair, making a direct edge check easy but using Θ(V²) space for V vertices. Whichever representation we choose, we must agree whether an edge has a direction, weight, or both.

Breadth-first search (BFS) begins at one vertex and visits all vertices one edge away before moving to those two edges away. It uses a queue. In an unweighted graph, it gives the fewest-edge path from the start to each reachable vertex. A visited mark prevents cycles from making us process the same vertex forever.

# Begin with the chosen starting vertex.
mark start visited and put it in a queue
while the queue is not empty:
    # The oldest waiting vertex is processed next.
    remove the front vertex u
    for each neighbor v of u:
        if v has not been visited:
            mark v visited and put v in the queue

Breadth-first search starts at A, visits B and C one edge away, then D and E two edges away

The first layer is A alone. B and C are one edge away; D and E are two. Their order within a layer depends on the order in which the neighbors are examined.

Depth-first search (DFS) follows one path as far as it can, then backs up. A stack, or recursive calls, keeps track of where to return. DFS helps detect cycles and determine finish times. With adjacency lists, both BFS and DFS take Θ(V + E) time to traverse the whole graph: each vertex is handled a bounded number of times and each edge is examined a bounded number of times.

If a directed graph has no cycle, it is a DAG. A topological order puts every prerequisite before the task that depends on it. For example, “write draft → review draft → publish” has an order, while “A needs B and B needs A” cannot have one. DFS finish times or an indegree-based queue can produce a topological order in Θ(V + E) time. A cycle means no such order exists.

In a directed graph, a strongly connected component is a maximal group in which every vertex can reach every other. Contract each such group into one vertex and the resulting component graph has no directed cycle. This helps us see which parts of a system can circulate among themselves and which paths move one way between groups.

Let A connect to B and C, and B connect to D. Start with queue [A], distance zero for A, and other vertices unseen. Remove A, discover B and C, assign both distance one, and queue them. Remove B, discover D, assign distance two, and put D behind C. Processing C cannot move D into an earlier layer.

Mark a vertex when it enters the queue, rather than when it leaves. Otherwise two neighbors may enqueue it repeatedly. Each vertex is queued once and each adjacency-list entry is examined once, giving Θ(V+E) time for a full traversal.

To report a route, remember each discovered vertex’s predecessor. Distances alone give lengths, not the sequence of vertices.

Practice. In an unweighted graph, why does BFS find a path with the fewest edges while DFS may not? What would prevent tasks from having a topological order?

Answer. BFS explores vertices in layers of increasing path length, so the first route to a vertex uses the fewest edges. DFS may follow a long route first. A directed cycle prevents any order that puts every prerequisite before its dependent task.

Try another case. What happens to an isolated vertex when BFS starts in another component?

Reasoning. It remains undiscovered, with no finite distance from that start. Traversing the whole graph requires starting another search from each still-unseen component.

View the full course and choose another topic.

Image preview

Fit