Depth-first search follows an edge as far as it can, then backtracks. It uses recursion (the call stack) or an explicit stack, plus a visited array. DFS is the foundation for finding connected components, detecting cycles, and topological sorting, and runs in O(V + E) with lists.
Remember
void dfs(int u) {
visited[u] = 1;
for (int v = 0; v < V; v++)
if (adj[u][v] && !visited[v]) dfs(v);
}
Reference
Cheat Sheet
Keep these facts handy while you work with Depth-First Search (DFS) in C in C.
Topic
Detail
Structure
Recursion / stack
Visited
Prevents cycles
Time
O(V + E) with lists
Uses
Components, cycles, ordering
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Graph Applications.
Example 1 — DFS order
The same graph as the BFS example.
C
#include <stdio.h>
#define V 6
static int adj[V][V], visited[V];
static void dfs(int u) {
visited[u] = 1;
printf(" %d", u);
for (int v = 0; v < V; v++)
if (adj[u][v] && !visited[v]) dfs(v);
}
int main(void) {
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;
}
printf("DFS order:");
dfs(0);
printf("\n");
return 0;
}
Output
DFS order: 0 1 4 3 2 5
How It Works
From 0, DFS goes to 1, then 4 (a dead end), and backtracks.
It returns to 0 and takes 3, then 2, then 5.
Compare with BFS order 0 1 3 4 2 5: depth first goes deep before wide.
Example 2 — Count connected components
Start a DFS from every unvisited vertex.
C
#include <stdio.h>
#define V 5
static int adj[V][V], visited[V];
static void dfs(int u) {
visited[u] = 1;
for (int v = 0; v < V; v++)
if (adj[u][v] && !visited[v]) dfs(v);
}
int main(void) {
int edges[][2] = {{0, 1}, {2, 3}, {3, 4}};
for (int i = 0; i < 3; i++) {
adj[edges[i][0]][edges[i][1]] = 1;
adj[edges[i][1]][edges[i][0]] = 1;
}
int components = 0;
for (int v = 0; v < V; v++) {
if (!visited[v]) {
components++;
dfs(v);
}
}
printf("components: %d\n", components);
return 0;
}
Output
components: 2
How It Works
The first DFS from 0 reaches 0 and 1.
The next unvisited vertex, 2, starts a second DFS reaching 2, 3, and 4.
Each fresh DFS start means one more component.
Edge Cases & Pitfalls
Check these before relying on Depth-First Search (DFS) in C in real programs.
deep
Deep recursion
A long path can overflow the call stack; use an explicit stack for huge graphs.
visit
No visited array
Cycles cause infinite recursion.
Remember
Key Takeaways
Go deep, then backtrack.
Visited is mandatory.
Components: one DFS per component.
One line: Depth-first search follows an edge as far as it can, then backtracks.
Frequently Asked Questions
A traversal that explores as far as possible along each branch before backtracking, using recursion or a stack.
Run DFS (or BFS) from each unvisited vertex and count how many times you start a new search.
Continue with "C Graph Applications" next. Check reachability and suggest friends in a social graph. The C Graphs hub lists every topic in order.