Skip to main content

BFS and DFS with example

Short answer

DFS uses a stack to go deep; BFS uses a queue to visit level by level. In the example graph with A connected to B and C, B to D and E, C to F, and E-F, DFS from A gives A B D E F C, while BFS gives A B C D E F. Both have O(V+E) time.

Explain depth first traversal and breadth first traversal in graph with suitable example.

Depth first traversal (DFS)

Goes as deep as possible along each path, then backtracks. Uses a stack (or recursion). From a vertex, move to an unvisited neighbour; when none remains, pop back.

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

Breadth first traversal (BFS)

Visits the start vertex, then all its neighbours, then their neighbours, level by level. Uses a queue.

int adj[N][N], visited[N], n;
void bfs(int s) {
    int queue[N], front = 0, rear = 0;
    visited[s] = 1; queue[rear++] = s;
    while (front < rear) {
        int v = queue[front++];            /* dequeue */
        printf("%d ", v);
        for (int w = 0; w < n; w++)
            if (adj[v][w] && !visited[w]) {
                visited[w] = 1;
                queue[rear++] = w;         /* enqueue */
            }
    }
}

Example graph

        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.

BFS from A (queue):

StepDequeuedNewly enqueuedQueue after stepOutput
0-AA
1AB, CB CA
2BD, EC D EA B
3CFD E FA B C
4DnoneE FA B C D
5Enone (F already queued)FA B C D E
6FnoneemptyA B C D E F

BFS order: A B C D E F

DFS from A (stack, alphabetical order): A → B → D (dead end, back to B) → E → F → C.

DFS order: A B D E F C

Both take O(V + E) time with adjacency lists.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 10 questions →