1. Gyanastra
  2. Algorithms
  3. Graph Traversal, DFS Applications, Topological Sort and SCC
  4. Graph Representations and Breadth-First Search
Free lesson, no account needed 12 min read 10 practice questions after it
Asked in past papers2 times
  • GATE CSE2014
  • UGC NET2006

Algorithms · Graph Traversal, DFS Applications, Topological Sort and SCC

Graph Representations and Breadth-First Search

A graph G=(V,E)G=(V,E) is a set of vertices VV and edges EE. Almost every graph algorithm (shortest paths, cycle detection, topological sort, connectivity, bipartiteness, SCC) begins by visiting every vertex in a disciplined order. The two disciplined orders are:

  • BFS (Breadth-First Search) — explore in "rings" of increasing distance from a source. Uses a queue.
  • DFS (Depth-First Search) — go as deep as possible, then backtrack. Uses a stack (or recursion).

Throughout, let n=∣V∣n=|V| and m=∣E∣m=|E|. (GATE questions use both V,EV,E and n,mn,m; they mean the same thing.)


2.1 Adjacency matrix

An n×nn\times n array AA with A[i][j]=1A[i][j]=1 if edge (i,j)∈E(i,j)\in E, else 00. Undirected graphs give a symmetric matrix; weighted graphs store the weight (and ∞\infty for no edge).

2.2 Adjacency list

An array of nn lists; list ii contains every neighbour of ii. Undirected edge {u,v}\{u,v\} appears twice (once in uu's list, once in vv's); directed edge u→vu\to v appears once.

2.3 Cost table (memorise this)

OperationAdjacency matrixAdjacency list
SpaceΘ(V2)\Theta(V^2)Θ(V+E)\Theta(V+E) (directed), Θ(V+2E)\Theta(V+2E) (undirected)
Test if (u,v)∈E(u,v)\in EO(1)O(1)O(deg⁡(u))O(\deg(u))
List all neighbours of uuΘ(V)\Theta(V)Θ(deg⁡(u))\Theta(\deg(u))
Add edgeO(1)O(1)O(1)O(1)
Remove edgeO(1)O(1)O(deg⁡(u))O(\deg(u))
Add vertexO(V2)O(V^2) (reallocate)O(1)O(1)
Total time to scan all edgesΘ(V2)\Theta(V^2)Θ(V+E)\Theta(V+E)
BFS / DFS timeΘ(V2)\Theta(V^2)Θ(V+E)\Theta(V+E)

Key consequence: BFS and DFS are Θ(V+E)\Theta(V+E) on lists but Θ(V2)\Theta(V^2) on a matrix, because with a matrix you must scan an entire row of length VV to find the (possibly few) neighbours of a vertex.

Which representation does GATE assume? If the question says "adjacency list" or "adjacency matrix", use that. If it says nothing and asks for the complexity of BFS/DFS, the standard answer is O(V+E)O(V+E) (list). If it says "dense graph" or "matrix", answer O(V2)O(V^2).


3.1 The algorithm

BFS(G, s):
  for each v in V:  colour[v] = WHITE;  d[v] = INF;  pi[v] = NIL
  colour[s] = GRAY;  d[s] = 0;  pi[s] = NIL
  Q = empty queue;  ENQUEUE(Q, s)
  while Q not empty:
      u = DEQUEUE(Q)
      for each v in Adj[u]:
          if colour[v] == WHITE:
              colour[v] = GRAY
              d[v] = d[u] + 1
              pi[v] = u
              ENQUEUE(Q, v)
      colour[u] = BLACK
  • colour: WHITE = undiscovered, GRAY = discovered but not finished, BLACK = finished.
  • d[v]: number of edges on the shortest path from ss to vv (in an unweighted graph).
  • pi[v]: BFS-tree parent.

3.2 Worked trace on 7 vertices

Graph (undirected), vertices 1..71..7:

1 -- 2 -- 3
|    |    |
4 -- 5    6
     |
     7

Edges: {1,2},{1,4},{2,3},{2,5},{3,6},{4,5},{5,7}\{1,2\},\{1,4\},\{2,3\},\{2,5\},\{3,6\},\{4,5\},\{5,7\}.

Adjacency lists (sorted ascending, as GATE usually assumes):

VertexNeighbours
12, 4
21, 3, 5
32, 6
41, 5
52, 4, 7
63
75

Source s=1s=1. Trace (queue shown front-to-back):

StepDequeueQueue after processingdd values set this step
0—[1]d[1]=0d[1]=0
11[2, 4]d[2]=1, d[4]=1d[2]=1,\ d[4]=1
22[4, 3, 5]d[3]=2, d[5]=2d[3]=2,\ d[5]=2
34[3, 5](5 already GRAY, skip)
43[5, 6]d[6]=3d[6]=3
55[6, 7]d[7]=3d[7]=3
66[7]—
77[]—

Final distances: d[1]=0, d[2]=1, d[4]=1, d[3]=2, d[5]=2, d[6]=3, d[7]=3d[1]=0,\ d[2]=1,\ d[4]=1,\ d[3]=2,\ d[5]=2,\ d[6]=3,\ d[7]=3.

Check: d[7]=3d[7]=3 via 1→2→5→71\to2\to5\to7 (3 edges) — correct, no shorter path exists. d[6]=3d[6]=3 via 1→2→3→61\to2\to3\to6 — correct.

BFS tree (parent pointers):

        1
       / \
      2   4
     / \
    3   5
    |    \
    6     7

3.3 Properties

  1. Shortest paths in unweighted graphs. d[v]d[v] equals the minimum number of edges from ss to vv. Proof idea: BFS discovers vertices in non-decreasing order of dd; when vv is first discovered from uu, d[v]=d[u]+1d[v]=d[u]+1 is minimal.
  2. Levels. All vertices with the same dd form a level; BFS visits level kk entirely before level k+1k+1. The queue never contains vertices from more than two consecutive levels.
  3. BFS tree. The edges {(π[v],v)}\{(\pi[v],v)\} form a tree rooted at ss spanning exactly the vertices reachable from ss. Every non-tree edge of an undirected graph joins two vertices whose levels differ by at most 1 (it is a "cross" edge between same or adjacent levels — see §5.4).
  4. Complexity. Each vertex is enqueued at most once (O(V)O(V) total queue work); each adjacency list is scanned once (O(E)O(E) total). With lists: Θ(V+E)\Theta(V+E). With a matrix: Θ(V2)\Theta(V^2).
  5. BFS does not work for weighted graphs — use Dijkstra instead.

3.4 BFS order is not unique

The order in which neighbours are enqueued depends on the order of the adjacency lists. GATE questions exploit this: "which of the following is a valid BFS order?" — you must check that the order is consistent with some adjacency-list ordering, not a specific one.

Rule for checking a BFS order: simulate the queue. Start with ss; repeatedly take the next unprocessed vertex uu of the given sequence (it must already be in the queue) and look at its still-undiscovered neighbours: they must be the next entries of the sequence, in any order among themselves. Equivalently, every vertex other than ss must have an earlier neighbour (its parent = its earliest-listed neighbour), the distances dd must be non-decreasing along the sequence, and the parents' positions must be non-decreasing: children of an earlier vertex come before children of a later vertex. Example: ss adjacent to a,ba,b; aa adjacent to cc; bb adjacent to dd. The order s,a,b,d,cs,a,b,d,c is not a BFS order (the child dd of bb precedes the child cc of aa), although it satisfies "each vertex has a neighbour in the previous level".

Pages 1–2 of 2