To process a graph by program, we must store it in memory and visit its vertices in a systematic order.

Adjacency Matrix

An adjacency matrix of a graph with n vertices is an n × n matrix A in which A[i][j] = 1 if there is an edge from vertex i to vertex j, and 0 otherwise. For a weighted graph, A[i][j] holds the weight. For an undirected graph the matrix is symmetric. Checking whether an edge exists takes O(1) time, but the matrix needs O(n²) memory, which is wasteful for a sparse graph with few edges.

Adjacency List

An adjacency list keeps, for each vertex, a linked list of the vertices adjacent to it. It needs O(n + e) memory, where e is the number of edges, so it suits sparse graphs, which are the most common in practice. Finding all neighbours of a vertex is fast, but checking a particular edge needs a search of a list.

Definition: Graph traversal. The process of visiting every vertex of a graph in a systematic order, starting from a chosen source vertex.

Breadth-First Search (BFS)

BFS visits the source vertex first, then all its neighbours, then their unvisited neighbours, and so on, level by level. It uses a queue. Algorithm: mark the source visited and enqueue it. While the queue is not empty, dequeue a vertex, process it, and enqueue every unvisited neighbour, marking it visited. BFS finds the shortest path (fewest edges) in an unweighted graph, and is used in networks and social "degrees of separation".

Depth-First Search (DFS)

DFS goes as deep as possible along one path before backing up. It uses a stack, or recursion. Algorithm: visit the source and mark it. For each unvisited neighbour, call DFS on it. When a vertex has no unvisited neighbour, back up. DFS is used to detect cycles, to find connected components, for topological sorting of tasks, and to solve mazes. Both BFS and DFS take O(n + e) time with an adjacency list, and O(n²) with a matrix. A visited array is essential, since otherwise cycles would make the traversal loop forever.

Table 4.2: BFS and DFS

Feature BFS DFS
Data structure Queue Stack or recursion
Order Level by level Deep along a path
Finds Shortest path (unweighted) Cycles, components, topological order
Time (list) O(n + e) O(n + e)

Example 4.2: BFS and DFS orders

Problem: For the graph with edges 0-1, 0-2, 1-3, 1-4, 2-5, find the BFS and DFS orders from vertex 0, taking neighbours in increasing order.

Solution:

  1. BFS: visit 0, then its neighbours 1, 2, then 1's neighbours 3, 4, then 2's neighbour 5. Order: 0 1 2 3 4 5.
  2. DFS: 0, go to 1, go to 3, back to 1, go to 4, back to 0, go to 2, go to 5. Order: 0 1 3 4 2 5.

Result: BFS: 0 1 2 3 4 5. DFS: 0 1 3 4 2 5.

#include <stdio.h>
#define N 6
int g[N][N], vis[N];
void dfs(int v) {
    vis[v] = 1; printf("%d ", v);
    for (int w = 0; w < N; w++) if (g[v][w] && !vis[w]) dfs(w);
}
int main(void) {
    int e[][2] = {{0,1},{0,2},{1,3},{1,4},{2,5}};
    for (int i = 0; i < 5; i++)
        g[e[i][0]][e[i][1]] = g[e[i][1]][e[i][0]] = 1;
    int q[N], f = 0, r = 0, seen[N] = {0};
    q[r++] = 0; seen[0] = 1; printf("BFS: ");
    while (f < r) {
        int v = q[f++]; printf("%d ", v);
        for (int w = 0; w < N; w++)
            if (g[v][w] && !seen[w]) { seen[w] = 1; q[r++] = w; }
    }
    printf("\nDFS: "); dfs(0); printf("\n");
    return 0;
}

Output

BFS: 0 1 2 3 4 5
DFS: 0 1 3 4 2 5

Common mistakes

  • Forgetting the visited array, so that cycles cause endless loops.
  • Using a stack for BFS or a queue for DFS.
  • Choosing an adjacency matrix for a large sparse graph.

Key takeaways

  • An adjacency matrix uses O(n²) space, an adjacency list O(n + e).
  • BFS uses a queue and visits level by level.
  • DFS uses a stack or recursion and goes deep first.
  • Both take O(n + e) with adjacency lists.

Practice questions

  1. What is an adjacency matrix?
  2. Which traversal finds the shortest path in an unweighted graph?
  3. What data structure does DFS use?

Answers to the practice questions

  1. An n × n matrix with A[i][j] = 1 when there is an edge from i to j.
  2. Breadth-first search.
  3. A stack, or recursion.

Sources

  • Official BCA syllabus Data Structures, course code 25BCA402DS02, Unit IV