Depth-First Search (DFS) in C

Intermediate
8 min read
Updated: Nov 2026
2 examples

As Deep as Possible First

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);
}

Cheat Sheet

Keep these facts handy while you work with Depth-First Search (DFS) in C in C.

TopicDetail
StructureRecursion / stack
VisitedPrevents cycles
TimeO(V + E) with lists
UsesComponents, cycles, ordering

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;
}

How It Works

  1. From 0, DFS goes to 1, then 4 (a dead end), and backtracks.
  2. It returns to 0 and takes 3, then 2, then 5.
  3. 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;
}

How It Works

  1. The first DFS from 0 reaches 0 and 1.
  2. The next unvisited vertex, 2, starts a second DFS reaching 2, 3, and 4.
  3. 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.

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.

Next: Graph Applications

Check reachability and suggest friends in a social graph.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful