Skip to main content

Depth first traversal in graph

Short answer

Depth-first traversal explores as far as possible along a branch before backtracking, using a stack or recursion. For example, starting at A in graph A-B, A-C, B-D, B-E, C-F, E-F, DFS order is A B D E F C. Complexity O(V+E).

Explain Depth first traversal in graph with example.

Depth first traversal (DFS) visits the vertices of a graph by going as deep as possible along a path before backtracking. It starts from a source vertex, marks it visited, then moves to an unvisited neighbour, and continues until a vertex has no unvisited neighbour; then it backtracks to the previous vertex and tries the next neighbour. It uses a stack (or recursion).

Algorithm (using a stack)

DFS(G, start)
1. push start on stack, mark start visited, print it
2. while stack not empty
3.     v = top of stack
4.     if v has an unvisited neighbour w
5.         mark w visited, print w, push w
6.     else  pop stack          // backtrack

Recursive version:

int adj[N][N], visited[N], n;
void dfs(int v) {
    visited[v] = 1;
    printf("%d ", v);
    for (int w = 0; w < n; w++)
        if (adj[v][w] && !visited[w])
            dfs(w);
}

Example

        A
       / \
      B   C
     / \   \
    D   E---F

Edges: A-B, A-C, B-D, B-E, C-F, E-F. Adjacency lists (alphabetical): A: B, C; B: A, D, E; C: A, F; D: B; E: B, F; F: C, E.

Start at A, choosing neighbours in alphabetical order:

StepCurrentActionStack (bottom to top)Visited order
1Avisit AAA
2Bvisit BA BA B
3Dvisit DA B DA B D
4Dno new neighbour, popA BA B D
5Evisit EA B EA B D E
6Fvisit FA B E FA B D E F
7Cvisit C (from F)A B E F CA B D E F C
8-all visited, pop until empty

DFS order: A B D E F C

Complexity: O(V + E) with adjacency lists, O(V²) with an adjacency matrix. Uses: cycle detection, topological sort, connected components, path finding.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 10 questions →