Reading history

Graphs in C: Adjacency Matrix, List, BFS and DFS

5 min read 0 views

Learn graphs in C: adjacency matrix and adjacency list, breadth-first search, depth-first search, shortest unweighted paths and connected components.

A graph is a set of vertices (nodes) connected by edges. Road maps, social networks, web links, flight routes and computer networks are all graphs. Unlike trees, graphs can contain cycles and need not have a root. This lesson shows the two ways to store a graph in C and the two fundamental ways to explore one: breadth-first search (BFS) and depth-first search (DFS).

In this lesson you will learn

  • Graph vocabulary: directed, undirected, weighted, connected
  • Adjacency matrix vs adjacency list
  • BFS with a queue, and shortest paths in unweighted graphs
  • DFS with recursion
  • Counting connected components

Graph Basics

TermMeaning
Undirected / directedEdges work both ways (friendship) or one way (following someone)
WeightedEach edge has a cost, such as a distance
DegreeNumber of edges touching a vertex
Path / cycleA route along edges / a route that returns to its start
Connected componentA group of vertices that can all reach each other

BFS and DFS on an Adjacency Matrix

#include <stdio.h>

#define V 6

/* Undirected graph stored as an adjacency matrix
   0 - 1, 0 - 2, 1 - 3, 2 - 4, 3 - 4, 3 - 5 */
int adj[V][V];

void add_edge(int u, int v) { adj[u][v] = adj[v][u] = 1; }

void bfs(int start) {
    int visited[V] = {0}, dist[V] = {0};
    int queue[V], front = 0, back = 0;
    visited[start] = 1;
    queue[back++] = start;
    printf("BFS from %d: ", start);
    while (front < back) {
        int u = queue[front++];
        printf("%d ", u);
        for (int v = 0; v < V; v++) {
            if (adj[u][v] && !visited[v]) {
                visited[v] = 1;
                dist[v] = dist[u] + 1;
                queue[back++] = v;
            }
        }
    }
    printf("\nDistance (number of edges) from %d: ", start);
    for (int v = 0; v < V; v++) printf("%d->%d ", v, dist[v]);
    printf("\n");
}

int visited_dfs[V];

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

int main(void) {
    add_edge(0, 1); add_edge(0, 2); add_edge(1, 3);
    add_edge(2, 4); add_edge(3, 4); add_edge(3, 5);

    bfs(0);
    printf("DFS from 0: ");
    dfs(0);
    printf("\n");
    return 0;
}

Output

BFS from 0: 0 1 2 3 4 5 
Distance (number of edges) from 0: 0->0 1->1 2->1 3->2 4->2 5->3 
DFS from 0: 0 1 3 4 2 5
  • The adjacency matrix adj[u][v] is 1 when an edge connects u and v. For an undirected graph it is symmetric, so add_edge sets both directions.
  • BFS uses a queue and explores in rings: first the start, then all its neighbours, then their neighbours. Because of that, the first time BFS reaches a vertex is along a path with the fewest edges, so it finds shortest paths in unweighted graphs. Vertex 5 is 3 edges from 0.
  • DFS goes as deep as possible along one path before backing up, here using recursion (an explicit stack works too). From 0 it runs 0 → 1 → 3 → 4 → 2, backs up to 3, and then visits 5.
  • The visited array is essential. Without it, cycles such as 0-1-3-4-2-0 would make the search loop forever.

Adjacency Lists and Connected Components

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

/* Adjacency list: each vertex keeps a linked list of neighbours */
struct Edge { int to; struct Edge *next; };

#define V 7
struct Edge *head[V];

void add_edge(int u, int v) {
    struct Edge *e = malloc(sizeof *e);
    if (!e) exit(1);
    e->to = v; e->next = head[u]; head[u] = e;
}

int visited[V];

void dfs(int u) {
    visited[u] = 1;
    for (struct Edge *e = head[u]; e; e = e->next)
        if (!visited[e->to]) dfs(e->to);
}

int main(void) {
    /* Three separate groups: {0,1,2}, {3,4}, {5,6} */
    int edges[][2] = {{0, 1}, {1, 2}, {3, 4}, {5, 6}};
    for (int i = 0; i < 4; i++) {
        add_edge(edges[i][0], edges[i][1]);
        add_edge(edges[i][1], edges[i][0]);
    }

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

    for (int u = 0; u < V; u++) {
        struct Edge *e = head[u];
        while (e) { struct Edge *n = e->next; free(e); e = n; }
    }
    return 0;
}

Output

Connected components: 3
  • An adjacency list stores, for each vertex, a linked list of its neighbours. It uses memory proportional to V + E instead of V², which matters for large, sparse graphs such as social networks.
  • Starting a DFS from every vertex not yet visited, and counting how many times you start, gives the number of connected components: here three separate groups.
Adjacency matrixAdjacency list
MemoryO(V²)O(V + E)
Is u–v an edge?O(1)O(degree of u)
Visit all neighboursO(V)O(degree)
Best forSmall or dense graphsLarge, sparse graphs

With an adjacency list, BFS and DFS both run in O(V + E) time; with a matrix they take O(V²).

BFS or DFS?

  • BFS: fewest-edges paths, level-by-level problems, “degrees of separation”.
  • DFS: detecting cycles, topological sorting, connected components, maze solving and backtracking.
  • For weighted shortest paths, use Dijkstra’s algorithm.

Common Mistakes

  1. Forgetting the visited array, causing infinite loops on cycles.
  2. Marking a vertex visited when it is removed from the queue rather than when it is added, so it can be queued many times.
  3. Adding only one direction of an undirected edge.
  4. Using a V × V matrix for a huge sparse graph and running out of memory.

Practice Exercises

Exercise 1. In the first graph, what would BFS from vertex 5 print?

Show answer

5 3 1 4 0 2. From 5 the only neighbour is 3; 3’s neighbours are 1 and 4 (in index order); then 1 adds 0, and 4 adds 2.

Exercise 2. How can you detect a cycle in an undirected graph with DFS?

Show answer

Pass the parent vertex into each DFS call. If you meet a neighbour that is already visited and is not the parent you came from, there is a cycle.

Frequently Asked Questions

Is a tree a graph?

Yes. A tree is a connected graph with no cycles. With n vertices it always has exactly n − 1 edges.

Why does BFS find shortest paths only in unweighted graphs?

BFS counts edges, not distances. A route with fewer but longer roads can be worse than one with more but shorter roads, so weighted graphs need Dijkstra’s algorithm.

Summary

  • Graphs model connections; store them as an adjacency matrix or list.
  • BFS uses a queue and finds fewest-edge paths.
  • DFS uses recursion or a stack and suits cycles, components and backtracking.
  • Both run in O(V + E) with adjacency lists.

Next: Dijkstra’s Algorithm in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *