Almost every graph algorithm is a variation of BFS (queue) or DFS (stack or recursion). BFS explores by distance; DFS explores deeply and backtracks. An iterative DFS replaces the call stack with an explicit stack: pop a vertex, visit it if new, and push its unvisited neighbors (in reverse index order to mimic the recursive order).
Example 1 — Iterative DFS and BFS on the same graph
Edges: 0-1, 0-3, 1-4, 2-3, 2-5.
C
#include <stdio.h>
#define V 6
int main(void) {
int adj[V][V] = {{0}};
int edges[][2] = {{0, 1}, {0, 3}, {1, 4}, {2, 3}, {2, 5}};
for (int i = 0; i < 5; i++) {
adj[edges[i][0]][edges[i][1]] = 1;
adj[edges[i][1]][edges[i][0]] = 1;
}
int visited[V] = {0}, stack[32], top = -1;
stack[++top] = 0;
printf("DFS:");
while (top >= 0) {
int u = stack[top--];
if (visited[u]) continue;
visited[u] = 1;
printf(" %d", u);
for (int v = V - 1; v >= 0; v--)
if (adj[u][v] && !visited[v]) stack[++top] = v;
}
int seen[V] = {0}, q[V], head = 0, tail = 0;
q[tail++] = 0;
seen[0] = 1;
printf("\nBFS:");
while (head < tail) {
int u = q[head++];
printf(" %d", u);
for (int v = 0; v < V; v++)
if (adj[u][v] && !seen[v]) { seen[v] = 1; q[tail++] = v; }
}
printf("\n");
return 0;
}
Output
DFS: 0 1 4 3 2 5
BFS: 0 1 3 4 2 5
How It Works
DFS pops 0, pushes 3 then 1, so 1 is explored first and then 4 before it backs up to 3.
BFS visits every neighbor of 0 (1 and 3) before going deeper.
The only structural difference is a stack versus a queue.
Edge Cases & Pitfalls
Check these before relying on Graph Traversal Review in C in real programs.
stack
Marking visited only on push
In iterative DFS, mark on pop, or you may skip valid paths or visit out of order.
size
Stack size
A vertex can be pushed several times; size the stack for up to E entries.
Remember
Key Takeaways
BFS: queue.
DFS: stack.
Both O(V + E) with lists.
One line: Almost every graph algorithm is a variation of BFS (queue) or DFS (stack or recursion).
Frequently Asked Questions
Use an explicit stack: push the start vertex, then repeatedly pop a vertex, visit it if unvisited, and push its neighbors.
Use BFS for shortest paths in unweighted graphs; use DFS for connectivity, cycle detection, and topological sorting.
Continue with "Cycle Detection in Graphs in C" next. Detect cycles in undirected and directed graphs using DFS. The C Graph Algorithms hub lists every topic in order.