Every graph algorithm starts with the same fundamental question: how do we visit every node? Answering that question efficiently is the job of the two core traversal algorithms — Breadth-First Search (BFS) and Depth-First Search (DFS).
By the end of this post you’ll understand how both work, when to use each, and how DFS extends naturally into topological sort — one of the most useful tools in any developer’s toolkit.
This is Part 2 of a 3-part series. Start with Part 1 if you haven’t yet.
The Node Status Model
Before writing any traversal code, it helps to think of nodes as having three possible states. Both BFS and DFS track these:
| Status | Meaning |
|---|---|
| UNDISCOVERED | Haven’t seen this node yet |
| DISCOVERED | Found it, but haven’t finished processing its neighbors |
| PROCESSED | Done — all neighbors explored |
cpp
enum Status { UNDISCOVERED, DISCOVERED, PROCESSED };
This three-state model is more useful than a simple visited boolean because it lets you detect cycles: if you reach a node that’s DISCOVERED but not yet PROCESSED, you’ve found a back edge (and therefore a cycle in a directed graph).
Breadth-First Search (BFS)
The Core Idea
BFS explores a graph level by level. Starting from a source node, it visits all immediate neighbors first, then their neighbors, and so on — like a ripple spreading across water.
BFS is your go-to when you need the shortest path in an unweighted graph. The first time BFS reaches a node, it’s guaranteed to have taken the minimum number of edges to get there.
Step-by-Step Walkthrough
Consider this graph (undirected):
Node 1 has neighbor 2, 3
Node 2 has neighbor 1, 4
Node 3 has neighbor 1, 4
Node 4 has neighbor 2, 3
Node 5 has neighbor 4
1
/ \
2 3
| |
4---+
|
5
Starting from node 1:
Step 1: Enqueue 1. Mark 1 DISCOVERED.
Queue: [1]
Step 2: Dequeue 1. Enqueue neighbors 2, 3. Mark them DISCOVERED. Mark 1 PROCESSED.
Queue: [2, 3]
Step 3: Dequeue 2. Enqueue neighbor 4. Mark 4 DISCOVERED. Mark 2 PROCESSED.
Queue: [3, 4]
Step 4: Dequeue 3. Neighbor 4 is already DISCOVERED — skip. Mark 3 PROCESSED.
Queue: [4]
Step 5: Dequeue 4. Enqueue 5. Mark 5 DISCOVERED. Mark 4 PROCESSED.
Queue: [5]
Step 6: Dequeue 5. No new neighbors. Mark 5 PROCESSED. Done ✓
Queue: []
Visit order: 1 → 2 → 3 → 4 → 5
BFS in C++
cpp
void bfs(unordered_map<int, vector<int>> &graph) {
queue<int> q;
vector<Status> status(graph.size(), UNDISCOVERED);
q.push(0);
status[0] = DISCOVERED;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : graph[u]) {
if (status[v] == UNDISCOVERED) {
q.push(v);
status[v] = DISCOVERED;
} else if (status[v] == DISCOVERED) {
// In a directed graph: cycle detected
// In an undirected graph: this is just the parent node
}
}
status[u] = PROCESSED;
}
}
Data structure: Queue (FIFO — first discovered, first explored) Time complexity: O(V + E) — each vertex and edge is touched once Space complexity: O(V) — the queue holds at most V nodes
Depth-First Search (DFS)
The Core Idea
DFS goes as deep as possible along one path before backtracking. Rather than spreading out like BFS, it dives straight down one branch, hits a dead end, unwinds, and tries the next branch.
DFS is naturally implemented with recursion (which uses the call stack implicitly). It’s the foundation for cycle detection, topological sort, and finding connected components.
Step-by-Step Walkthrough
Same graph as before, starting from node 1:
1
/ \
2 3
| |
4---+
|
5
Call dfs(1): Mark 1 DISCOVERED. Visit neighbor 2.
Call dfs(2): Mark 2 DISCOVERED. Visit neighbor 4.
Call dfs(4): Mark 4 DISCOVERED. Visit neighbor 5.
Call dfs(5): Mark 5 DISCOVERED. No new neighbors.
Mark 5 PROCESSED. ← first to finish
Mark 4 PROCESSED.
Mark 2 PROCESSED.
Back at node 1 — visit neighbor 3.
Call dfs(3): Mark 3 DISCOVERED. Neighbor 4 already PROCESSED — skip.
Mark 3 PROCESSED.
Mark 1 PROCESSED. Done ✓
Process order: 5 → 4 → 2 → 3 → 1 (nodes finish deepest-first)
DFS in C++
cpp
void dfs(const unordered_map<int, vector<int>> &graph,
int curr,
vector<Status> &status) {
status[curr] = DISCOVERED;
for (int neighbor : graph[curr]) {
if (status[neighbor] == UNDISCOVERED) {
dfs(graph, neighbor, status);
} else if (status[neighbor] == DISCOVERED) {
// Directed graph → back edge, cycle detected
// Undirected graph → this is the parent node
}
}
status[curr] = PROCESSED;
}
Data structure: Call stack (recursion) or explicit stack Time complexity: O(V + E) Space complexity: O(V) for the recursion stack
BFS vs. DFS: When to Use Which
| BFS | DFS | |
|---|---|---|
| Core structure | Queue | Stack / Recursion |
| Shortest path (unweighted) | Yes | No |
| Cycle detection | Yes | Yes |
| Topological sort | No | Yes |
| Memory (wide graphs) | Higher | Lower |
| Memory (deep graphs) | Lower | Higher (stack depth) |
| Time complexity | O(V + E) | O(V + E) |
Rule of thumb:
- Need shortest path in an unweighted graph? → BFS
- Need to explore all possibilities, detect cycles, or sort dependencies? → DFS
Topological Sort (DFS Extension)
Topological sort orders the vertices of a Directed Acyclic Graph (DAG) so that every edge points from left to right — meaning, every dependency comes before the thing that depends on it.
Classic example: course prerequisites
A ──► B ──► D ──► C
│ ▲ ▲
└───────────┘ ┘
└─────────────────┘
Edges: A→B, A→C, A→D, B→D, D→C
Suppose you need to take these courses, with prerequisites:
- A is required before B, C, and D
- A and B are required before D
- A, B, and D are required before C
The correct order to take them: A → B → D → C
If there’s a cycle in the graph (course X requires Y, and Y requires X), no valid order exists — topological sort is impossible.
The Algorithm
Topological sort is just DFS with one extra line: push each node onto a stack when it finishes (after all its successors are processed). Pop the stack at the end and that’s your order.
cpp
void dfs(const unordered_map<int, vector<int>> &graph,
int curr,
vector<Status> &status,
stack<int> &result) {
status[curr] = DISCOVERED;
for (int neighbor : graph.at(curr)) {
if (status[neighbor] == UNDISCOVERED) {
dfs(graph, neighbor, status, result);
} else if (status[neighbor] == DISCOVERED) {
// Cycle detected — topological sort impossible!
cout << "Cycle found. No topological order exists." << endl;
exit(1);
}
}
status[curr] = PROCESSED;
result.push(curr); // ← the only change from plain DFS
}
// In main():
stack<int> topSort;
dfs(graph, 0, status, topSort);
while (!topSort.empty()) {
cout << topSort.top() << " ";
topSort.pop();
}
Why the stack gives the right order: A node is pushed only after all of its successors have been pushed. So when you pop, successors always come out before the things they depend on — wait, the opposite: predecessors come out first. That’s exactly what we want.
Common Pitfalls
Disconnected graphs — if your graph has multiple components, a single BFS/DFS from one starting node won’t visit all vertices. Wrap your traversal in a loop that checks all nodes:
cpp
for (int i = 0; i < n; i++) {
if (status[i] == UNDISCOVERED) {
dfs(graph, i, status);
}
}
Stack overflow in DFS — deep recursive DFS on a graph with 10,000+ nodes can blow the call stack. For very deep graphs, convert to an iterative implementation using an explicit stack.
Summary
- BFS uses a queue, explores level by level, and finds shortest paths in unweighted graphs
- DFS uses recursion (or a stack), dives deep first, and is the basis for cycle detection and topological sort
- Both run in O(V + E) time with an adjacency list
- Topological sort = DFS + push to a result stack on node completion; only works on DAGs
In Part 3, we’ll tackle the advanced algorithms: Dijkstra’s shortest path for weighted graphs, Kruskal’s and Prim’s Minimum Spanning Tree algorithms, and the Union Find data structure that powers them.