DFS
Depth-first search walks a graph by descending into one neighbor as far as it can before it backtracks. Recursion or an explicit stack holds the path.
Detailed Explanation
From vertex u, mark u visited, then recurse on each unvisited neighbor. That is the recursive form. The iterative form pushes neighbors onto a stack. Both visit a connected component. Neither visits vertices in distance order; that is BFS.
DFS produces a tree of discovery plus back, forward, and cross edges, which is how you detect cycles in a directed graph: a back edge to a vertex on the current recursion stack. Three colors (white / gray / black) make that precise. In an undirected graph, a back edge to a visited vertex that is not the parent is a cycle.
Finishing times — the moment a vertex's recursion returns — give a topological order if you append to a list on exit and then reverse it, provided the graph is a DAG. Strongly connected components (Kosaraju, Tarjan) are DFS plus a second pass.
In C the recursive form is short and blows the stack on a path of length tens of thousands. An explicit int stack[n] and a loop are the production version for hostile or just large input. Either way you need visited. On a tree, passing the parent and not walking back is enough if you are sure it is a tree.
Preorder work happens before the recursive calls. Postorder work happens after. Freeing a tree is postorder. Emitting a prefix expression is preorder. Know which side of the call you are on.
DFS does not find unweighted shortest paths. It can find a path, usually a long one. Use BFS for fewest edges.
Code Examples
#include <stdio.h>
enum { N = 4 };
static void dfs(int u, int adj[N][N], char *seen)
{
seen[u] = 1;
printf("%d ", u);
for (int v = 0; v < N; v++) {
if (adj[u][v] && !seen[v]) {
dfs(v, adj, seen);
}
}
}
int main(void)
{
int adj[N][N] = {
{0, 1, 1, 0},
{0, 0, 0, 1},
{0, 0, 0, 0},
{0, 0, 0, 0},
};
char seen[N] = { 0 };
dfs(0, adj, seen); /* prints: 0 1 3 2 */
printf("\n");
return 0;
}#include <stdio.h>
/* Cycle detect in a directed graph: gray = on the stack. */
enum { N = 3, WHITE = 0, GRAY = 1, BLACK = 2 };
static int dfs_cycle(int u, int adj[N][N], int *color)
{
color[u] = GRAY;
for (int v = 0; v < N; v++) {
if (!adj[u][v]) {
continue;
}
if (color[v] == GRAY) {
return 1;
}
if (color[v] == WHITE && dfs_cycle(v, adj, color)) {
return 1;
}
}
color[u] = BLACK;
return 0;
}
int main(void)
{
int adj[N][N] = { {0, 1, 0}, {0, 0, 1}, {1, 0, 0} };
int color[N] = { 0 };
printf("%d\n", dfs_cycle(0, adj, color)); /* prints: 1 */
return 0;
}Common Gotchas
Recursing on a long path overflows the C stack
iterate with an explicit stack when `n` is large or untrusted.
`visited` alone does not detect directed cycles
you need "on the current path" (gray), not merely "already finished."
Neighbor order depends on how you stored the adjacency list
DFS's visit order is not unique.
DFS path length is not a shortest-path distance
DFS path length is not a shortest-path distance