Course contentsShow
← C
Lesson 1045 of 1,21914. Data Structures in CFree lesson

Depth-First Search (DFS) recursion

Depth-First Search (DFS) recursion

What you'll learn: How to use recursion to explore a graph by diving as deep as possible along each branch before backtracking.

The "Labyrinth" Approach

Imagine you are exploring a dark stone labyrinth. You have a ball of string and a piece of chalk. To ensure you don't get lost or walk in circles, you follow a simple rule: pick a path and follow it until you hit a dead end or a room you’ve already visited. When you can’t go any further, you follow your string back to the last intersection and try a different path.

In C, Depth-First Search (DFS) uses recursion to act as that string. It "dives" into the graph, visiting a node and immediately jumping to one of its neighbors, repeating this until it has to backtrack.

Marking Your Territory

Because graphs can have cycles (paths that lead back to the start), a DFS will run forever if you don't keep track of where you've been. We typically use a visited array—an array of booleans where visited[i] is true if we have already processed node i.

The Recursive Logic

The beauty of DFS is its simplicity when written recursively. The function does three things:

  1. Mark the current node as visited.
  2. Perform whatever action is needed (like printing the node).
  3. Look at all neighbors of the current node. If a neighbor hasn't been visited, call the DFS function again for that neighbor.
#include <stdio.h>
#include <stdbool.h>

#define V 5 // Number of vertices

void DFS(int adj[V][V], bool visited[V], int vertex) {
    // 1. Mark the current node as visited
    visited[vertex] = true;
    printf("Visited node: %d\n", vertex);

    // 2. Check all possible neighbors
    for (int i = 0; i < V; i++) {
        // If there is an edge AND we haven't been there yet
        if (adj[vertex][i] == 1 && !visited[i]) {
            // 3. Dive deeper!
            DFS(adj, visited, i);
        }
    }
}

Why It Works

When DFS calls itself, the computer puts the current node on the "Stack." It stays there, waiting, while the code explores the new branch. Once that branch is fully explored (all neighbors are visited), the function finishes, and the computer "pops" back to the previous node to check its remaining neighbors. This creates the "deep" movement characteristic of this algorithm.

Key takeaway

DFS uses recursion to explore a graph's depth by visiting a node and immediately moving to an unvisited neighbor, using a visited array to prevent infinite loops.