Skip to content
Laviyx Learn

Try

DS Lab · Experiment 17

Graph traversals (BFS and DFS)

CGraphsJNTUH R22 · CS306PC

Aim

To write a C program that reads a graph as an adjacency matrix and prints its breadth-first search (BFS) and depth-first search (DFS) traversal orders from a given start vertex.

Algorithm

  1. Read the number of vertices n, the n × n adjacency matrix (adj[i][j] is 1 if there is an edge from i to j) and the start vertex.
  2. BFS: mark all vertices unvisited. Mark the start vertex visited and put it in a queue.
  3. While the queue is not empty, remove a vertex v and print it. For every vertex w from 0 to n − 1 with adj[v][w] == 1 that is not visited, mark w visited and add it to the queue.
  4. DFS: mark all vertices unvisited again and call dfs(start).
  5. dfs(v): mark v visited and print it. For every vertex w from 0 to n − 1 with adj[v][w] == 1 that is not visited, call dfs(w).
  6. Print both orders.

Program

C
#include <stdio.h>

#define MAX 10

int adj[MAX][MAX];
int visited[MAX];
int n;

void bfs(int start) {
    int queue[MAX];
    int front = 0, rear = 0;

    for (int i = 0; i < n; i++) {
        visited[i] = 0;
    }
    visited[start] = 1;             /* mark when added, so no vertex is queued twice */
    queue[rear++] = start;

    while (front < rear) {
        int v = queue[front++];
        printf("%d ", v);
        for (int w = 0; w < n; w++) {
            if (adj[v][w] == 1 && !visited[w]) {
                visited[w] = 1;
                queue[rear++] = w;
            }
        }
    }
}

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

int main(void) {
    int start;

    printf("Enter number of vertices (1-%d): ", MAX);
    if (scanf("%d", &n) != 1 || n < 1 || n > MAX) {
        printf("Invalid number of vertices\n");
        return 1;
    }
    printf("Enter the adjacency matrix (%d rows of %d values, 0 or 1):\n", n, n);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (scanf("%d", &adj[i][j]) != 1) {
                printf("Invalid input\n");
                return 1;
            }
        }
    }
    printf("Enter start vertex (0-%d): ", n - 1);
    if (scanf("%d", &start) != 1 || start < 0 || start >= n) {
        printf("Invalid start vertex\n");
        return 1;
    }

    printf("BFS traversal: ");
    bfs(start);
    printf("\n");

    for (int i = 0; i < n; i++) {
        visited[i] = 0;
    }
    printf("DFS traversal: ");
    dfs(start);
    printf("\n");
    return 0;
}

Output

Start at vertex 0

Output 1
Enter number of vertices (1-10): 6
Enter the adjacency matrix (6 rows of 6 values, 0 or 1):
0 1 1 0 0 0
1 0 0 1 1 0
1 0 0 0 1 0
0 1 0 0 0 1
0 1 1 0 0 1
0 0 0 1 1 0
Enter start vertex (0-5): 0
BFS traversal: 0 1 2 3 4 5 
DFS traversal: 0 1 3 5 4 2 

Start at vertex 3

Output 2
Enter number of vertices (1-10): 6
Enter the adjacency matrix (6 rows of 6 values, 0 or 1):
0 1 1 0 0 0
1 0 0 1 1 0
1 0 0 0 1 0
0 1 0 0 0 1
0 1 1 0 0 1
0 0 0 1 1 0
Enter start vertex (0-5): 3
BFS traversal: 3 1 5 0 4 2 
DFS traversal: 3 1 0 2 4 5 

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

Vertices are numbered from 0. The matrix in both runs is this undirected graph, with edges 0–1, 0–2, 1–3, 1–4, 2–4, 3–5 and 4–5:

Text
    0
   / \
  1   2
 / \ /
3   4
 \ /
  5

From vertex 0, BFS visits by distance: 0, then its neighbours 1 and 2, then 3 and 4 (distance 2), then 5. DFS goes as deep as it can first: 0 → 1 → 3 → 5 → 4 → 2. When a vertex has several unvisited neighbours, both programs take the smallest number first, which is why the orders are exactly these.

Only vertices reachable from the start vertex are printed. For a disconnected graph, call the traversal again from each vertex that is still unvisited.

Common mistakes

  • Marking a vertex visited only when it is removed from the BFS queue. The same vertex can then be added to the queue several times. Mark it when it is added.

  • Forgetting to reset the visited array between BFS and DFS, so the second traversal prints only the start vertex.

  • Entering the matrix for an undirected graph with only one direction of an edge (adj[i][j] = 1 but adj[j][i] = 0). For an undirected graph the matrix must be symmetric.

  • Expecting a single 'correct' answer. The order depends on the order in which neighbours are checked; this program checks them from 0 to n − 1.

Viva questions

Try to answer each one aloud before you open it.

  • What is the difference between BFS and DFS?

    BFS visits vertices level by level, all neighbours of a vertex before going further, using a queue. DFS goes as deep as possible along one path before backtracking, using a stack or recursion.

  • What is the time complexity of BFS and DFS?

    O(V²) with an adjacency matrix, because every row is scanned. With an adjacency list it is O(V + E), where V is the number of vertices and E the number of edges.

  • Why do we need a visited array?

    A graph can have cycles. Without marking visited vertices, the traversal could go round a cycle forever or print a vertex many times.

  • Which traversal finds the shortest path in an unweighted graph?

    BFS. It reaches every vertex first by a path with the fewest edges.

  • Give some applications of DFS.

    Finding connected components, detecting cycles, topological sorting, and solving mazes.

  • What is an adjacency matrix, and when is an adjacency list better?

    An n × n matrix where entry (i, j) is 1 if there is an edge from i to j. An adjacency list uses less memory and is faster to traverse for sparse graphs, which have few edges.

Learn the concepts

All Data Structures Lab experiments →