Skip to content
StudyFame

Graphs, BFS and DFS in C

Cities joined by roads, friends on a social network, web pages linked to each other: all of these are graphs. A graph is a set of vertices (points) connected by edges (lines). Unlike a tree, a graph can have cycles, and any vertex can connect to any other.

In this lesson you will learn graph terminology, two ways to store a graph in C (adjacency matrix and adjacency list), and the two basic ways to explore it: BFS (Breadth-First Search) with a queue and DFS (Depth-First Search) with recursion. You will also count connected components and find shortest paths in an unweighted graph.

What You Will Learn

  • Graph terms: vertex, edge, directed, undirected, weighted, degree, path, cycle.
  • Adjacency matrix vs adjacency list.
  • Breadth-First Search (BFS) using a queue.
  • Depth-First Search (DFS) using recursion.
  • Why a visited array is needed.
  • Applications: connected components, shortest path in unweighted graphs.

Graphs, BFS and DFS in C Explained

Exam definition: A graph G = (V, E) is a non-linear data structure consisting of a set of vertices V and a set of edges E, where each edge connects a pair of vertices. A graph is directed if edges have a direction and undirected otherwise; it is weighted if edges carry costs. BFS visits vertices level by level from a source using a queue; DFS goes as deep as possible along each branch before backtracking, using a stack or recursion. Both run in O(V + E) with an adjacency list and O(V²) with an adjacency matrix.

Memory trick: You lost your keys at home. BFS = search room by room in rings: first all rooms next to you, then rooms two doors away (like ripples in water). DFS = walk down one corridor to the very end, then come back and try the next corridor (like exploring a maze). Either way, mark every room you've checked (visited) so you don't search it twice.

Undirected graph with 6 vertices:

      0 ───── 1 ───── 3
      │       │       │
      │       │       │
      2 ───── 4 ───── 5

Edges: 0-1, 0-2, 1-3, 1-4, 2-4, 3-5, 4-5
Degree of 1 = 3 (neighbours 0, 3, 4)       Path 0 → 1 → 3 → 5       Cycle 0-1-4-2-0

Syntax: Storing a Graph

Adjacency matrix

#define V 6
int adj[V][V];            /* adj[i][j] = 1 if there is an edge i-j, else 0 */
adj[0][1] = adj[1][0] = 1; /* undirected: set both directions */

Adjacency list

struct edge
{
    int to;
    struct edge *next;
};
struct edge *list[V];     /* list[i] = linked list of i's neighbours */
PointAdjacency matrixAdjacency list
MemoryO(V²)O(V + E)
Is there an edge i–j?O(1): look at adj[i][j]O(degree of i)
Visit all neighbours of iO(V)O(degree of i)
Best forDense graphs, small VSparse graphs (most real graphs)

Example 1: Adjacency Matrix, BFS and DFS

#include <stdio.h>

#define V 6

int adj[V][V];
int visited[V];

void add_edge(int a, int b)
{
    adj[a][b] = adj[b][a] = 1;      /* undirected */
}

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

    for (v = 0; v < V; v++)
        visited[v] = 0;
    visited[start] = 1;
    queue[rear++] = start;

    printf("BFS from %d: ", start);
    while (front < rear)
    {
        u = queue[front++];
        printf("%d ", u);
        for (v = 0; v < V; v++)
            if (adj[u][v] && !visited[v])
            {
                visited[v] = 1;          /* mark when enqueued */
                queue[rear++] = v;
            }
    }
    printf("\n");
}

void dfs(int u)
{
    int v;
    visited[u] = 1;
    printf("%d ", u);
    for (v = 0; v < V; v++)
        if (adj[u][v] && !visited[v])
            dfs(v);                      /* go deeper first */
}

int main(void)
{
    int i, j;

    add_edge(0, 1); add_edge(0, 2); add_edge(1, 3);
    add_edge(1, 4); add_edge(2, 4); add_edge(3, 5); add_edge(4, 5);

    printf("Adjacency matrix:\n   ");
    for (j = 0; j < V; j++)
        printf("%d ", j);
    printf("\n");
    for (i = 0; i < V; i++)
    {
        printf("%d: ", i);
        for (j = 0; j < V; j++)
            printf("%d ", adj[i][j]);
        printf("\n");
    }

    bfs(0);

    for (i = 0; i < V; i++)
        visited[i] = 0;
    printf("DFS from 0: ");
    dfs(0);
    printf("\n");
    return 0;
}

Output

Adjacency matrix:
   0 1 2 3 4 5
0: 0 1 1 0 0 0
1: 1 0 0 1 1 0
2: 1 0 0 0 1 0
3: 0 1 0 0 0 1
4: 0 1 1 0 0 1
5: 0 0 0 1 1 0
BFS from 0: 0 1 2 3 4 5
DFS from 0: 0 1 3 5 4 2 

Code Explanation

  1. The matrix is symmetric because the graph is undirected: adj[0][1] and adj[1][0] are both 1.
  2. BFS starts at 0, enqueues its neighbours 1 and 2, then 1's unvisited neighbours 3 and 4, then 3's neighbour 5. Vertices come out in order of distance from 0: 0 (distance 0), 1 2 (distance 1), 3 4 (distance 2), 5 (distance 3).
  3. BFS marks a vertex as visited when it is enqueued, so it is never added to the queue twice.
  4. DFS goes 0 → 1 → 3 → 5 as deep as possible, then from 5 it finds unvisited 4, and from 4 it finds unvisited 2. Only then does it backtrack.
  5. Without the visited array, the cycle 0-1-4-2-0 would make DFS and BFS run forever.

How BFS and DFS Explore

BFS (queue)                          DFS (recursion = call stack)
queue: [0]          visit 0           dfs(0) -> dfs(1) -> dfs(3) -> dfs(5)
queue: [1 2]        visit 1           dfs(5): 3 visited, try 4 -> dfs(4)
queue: [2 3 4]      visit 2           dfs(4): 1 visited, try 2 -> dfs(2)
queue: [3 4]        visit 3           dfs(2): all neighbours visited, return
queue: [4 5]        visit 4           ... back to dfs(0): all done
queue: [5]          visit 5
Order: 0 1 2 3 4 5                   Order: 0 1 3 5 4 2
PointBFSDFS
Data structureQueueStack / recursion
OrderLevel by level (nearest first)Deep along one path, then backtrack
Shortest path (unweighted)YesNo
UsesShortest path, social "friends of friends", web crawlingCycle detection, mazes, topological sort, components
TimeO(V + E) with a list, O(V²) with a matrix

Example 2: Adjacency List and Connected Components

#include <stdio.h>
#include <stdlib.h>

#define V 7

struct edge
{
    int to;
    struct edge *next;
};

struct edge *list[V];
int visited[V];

void add_directed(int a, int b)
{
    struct edge *e = malloc(sizeof *e);
    if (e == NULL)
        exit(1);
    e->to = b;
    e->next = list[a];          /* insert at the front of a's list */
    list[a] = e;
}

void add_edge(int a, int b)
{
    add_directed(a, b);
    add_directed(b, a);
}

void dfs(int u)
{
    struct edge *e;
    visited[u] = 1;
    printf("%d ", u);
    for (e = list[u]; e != NULL; e = e->next)
        if (!visited[e->to])
            dfs(e->to);
}

int main(void)
{
    struct edge *e, *t;
    int i, components = 0;

    add_edge(0, 1);
    add_edge(1, 2);
    add_edge(3, 4);
    add_edge(5, 6);

    printf("Adjacency list:\n");
    for (i = 0; i < V; i++)
    {
        printf("%d:", i);
        for (e = list[i]; e != NULL; e = e->next)
            printf(" -> %d", e->to);
        printf("\n");
    }

    for (i = 0; i < V; i++)
        if (!visited[i])
        {
            components++;
            printf("Component %d: ", components);
            dfs(i);
            printf("\n");
        }
    printf("Connected components: %d\n", components);

    for (i = 0; i < V; i++)
        for (e = list[i]; e != NULL; e = t)
        {
            t = e->next;
            free(e);
        }
    return 0;
}

Output

Adjacency list:
0: -> 1
1: -> 2 -> 0
2: -> 1
3: -> 4
4: -> 3
5: -> 6
6: -> 5
Component 1: 0 1 2 
Component 2: 3 4 
Component 3: 5 6 
Connected components: 3
  • Each vertex has a linked list of its neighbours. Inserting at the front is O(1), which is why 1's list shows 2 before 0.
  • The list stores only the 8 directed entries that exist, instead of a 7 × 7 = 49-cell matrix. For big, sparse graphs this saves a lot of memory.
  • Every DFS started from an unvisited vertex reaches exactly one connected component; counting the starts counts the components: {0, 1, 2}, {3, 4}, {5, 6}.

Important Points to Remember

  • Graph = vertices + edges; can be directed/undirected and weighted/unweighted; may have cycles.
  • Adjacency matrix: O(V²) memory, O(1) edge check. Adjacency list: O(V + E) memory, best for sparse graphs.
  • BFS uses a queue and visits nearest vertices first; it finds shortest paths in unweighted graphs.
  • DFS uses a stack/recursion and goes deep first; used for cycles, mazes, components, topological sort.
  • Always keep a visited array, or cycles cause infinite loops.
  • Time: O(V + E) with a list, O(V²) with a matrix.

Common Mistakes Beginners Make

MistakeWhat happensFix
No visited arrayInfinite loop on cyclesMark vertices as visited
Setting only adj[a][b] for an undirected edgeEdge works in one direction onlySet adj[a][b] and adj[b][a]
Marking visited when dequeued in BFSA vertex can be enqueued many timesMark when enqueued
Not resetting visited between searchesSecond search visits nothingClear the array before each BFS/DFS
Using DFS for the shortest pathFinds a path, not the shortestUse BFS for unweighted shortest paths

Graph, BFS and DFS Practice Questions

  1. What is a graph? Differentiate between directed and undirected graphs.
  2. Compare adjacency matrix and adjacency list representations.
  3. Which data structure does BFS use? Which does DFS use?
  4. Why is a visited array necessary?
  5. Write the BFS order from vertex 0 for edges 0-1, 0-2, 1-3, 2-3.
Show answers
  1. A set of vertices connected by edges. Directed: edges have a direction (u → v). Undirected: edges go both ways.
  2. Matrix: V × V array, O(V²) memory, O(1) edge test, good for dense graphs. List: neighbour lists, O(V + E) memory, good for sparse graphs.
  3. BFS uses a queue; DFS uses a stack (or recursion).
  4. Graphs can have cycles; without marking, the search would revisit vertices forever.
  5. 0 1 2 3.

Coding Exercise

Using BFS on the 6-vertex graph from Example 1, compute the shortest distance (number of edges) from vertex 0 to every other vertex, and print the path from 0 to 5 using a parent array.

Show solution
#include <stdio.h>

#define V 6

int adj[V][V];

void add_edge(int a, int b) { adj[a][b] = adj[b][a] = 1; }

void print_path(const int parent[], int v)
{
    if (parent[v] != -1)
    {
        print_path(parent, parent[v]);
        printf(" -> ");
    }
    printf("%d", v);
}

int main(void)
{
    int dist[V], parent[V], queue[V], front = 0, rear = 0, u, v;

    add_edge(0, 1); add_edge(0, 2); add_edge(1, 3);
    add_edge(1, 4); add_edge(2, 4); add_edge(3, 5); add_edge(4, 5);

    for (v = 0; v < V; v++)
    {
        dist[v] = -1;
        parent[v] = -1;
    }
    dist[0] = 0;
    queue[rear++] = 0;
    while (front < rear)
    {
        u = queue[front++];
        for (v = 0; v < V; v++)
            if (adj[u][v] && dist[v] == -1)
            {
                dist[v] = dist[u] + 1;
                parent[v] = u;
                queue[rear++] = v;
            }
    }

    for (v = 0; v < V; v++)
        printf("Distance 0 to %d: %d\n", v, dist[v]);
    printf("Path 0 to 5: ");
    print_path(parent, 5);
    printf("\n");
    return 0;
}
Distance 0 to 0: 0
Distance 0 to 1: 1
Distance 0 to 2: 1
Distance 0 to 3: 2
Distance 0 to 4: 2
Distance 0 to 5: 3
Path 0 to 5: 0 -> 1 -> 3 -> 5

Because BFS reaches each vertex first along a shortest route, dist holds the minimum number of edges, and parent lets us rebuild the route backwards.

Quick Quiz: Graph, BFS and DFS (MCQ)

  1. BFS uses which data structure?

    A) Stack   B) Queue   C) Tree   D) Hash table

  2. The adjacency matrix of a graph with V vertices needs memory:

    A) O(V)   B) O(E)   C) O(V²)   D) O(log V)

  3. Which search finds the shortest path in an unweighted graph?

    A) DFS   B) BFS   C) Binary search   D) Linear search

  4. The adjacency matrix of an undirected graph is:

    A) Always diagonal   B) Symmetric   C) All ones   D) Upper triangular

  5. Time complexity of BFS/DFS with an adjacency list:

    A) O(V)   B) O(V + E)   C) O(V × E)   D) O(E²)

Show answers
  1. B: queue.
  2. C: O(V²).
  3. B: BFS.
  4. B: symmetric.
  5. B: O(V + E).

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

GraphG = (V, E): vertices and edges
Adjacency matrixO(V²) memory, O(1) edge check
Adjacency listO(V + E) memory, sparse graphs
BFSQueue, level by level, shortest path
DFSStack/recursion, deep first
visited[]Prevents infinite loops on cycles
TimeO(V + E) list, O(V²) matrix

Frequently asked questions

What is the difference between BFS and DFS?
BFS explores level by level with a queue; DFS goes as deep as possible first with a stack or recursion.
How is a graph represented in C?
With an adjacency matrix (2D array) or an adjacency list (array of linked lists of neighbours).
What is the difference between a tree and a graph?
A tree is a connected graph with no cycles and one root; a general graph can have cycles and many components.

Remember

  • BFS = ripples in water; DFS = exploring a maze.
  • Always keep a visited array.

Next Topic

Next lesson: Hashing in C. You will store and find data in O(1) average time with a hash table and chaining.