1. Gyanastra
  2. Algorithms
  3. UGC NET: Graph Algorithms Extras
  4. Bfs Dfs and Their Applications
Free lesson, no account needed 11 min read 10 practice questions after it
Asked in past papers2 times
  • GATE CSE2007
  • ISRO2018

Algorithms · UGC NET: Graph Algorithms Extras

Bfs Dfs and Their Applications

Overview

Breadth-First Search (BFS) and Depth-First Search (DFS) are the two fundamental graph traversal algorithms.
They are used to visit every reachable vertex, build a traversal tree, and solve problems such as shortest paths in unweighted graphs, cycle detection, topological sorting, and strongly connected components.
This lesson belongs to graph algorithm extras in DSA; it assumes you know vertices, edges, adjacency lists, adjacency matrices, directed and undirected graphs, trees, and basic complexity notation.
The exam tests both direct facts and subtle structural properties, especially edge classification, BFS distances, DFS timestamps, topological order, and Kosaraju’s SCC algorithm.

Key concepts

  • BFS (Breadth-First Search) explores vertices in nondecreasing order of distance from a source ss. It uses a FIFO queue.
  • DFS (Depth-First Search) explores one path as deep as possible before backtracking. It uses a LIFO stack, or recursion.
  • A BFS tree rooted at ss contains the discovery edges. For every reachable vertex vv, its depth in the BFS tree equals the shortest unweighted path length from ss to vv.
  • A DFS tree contains discovery edges of a DFS forest. DFS does not generally give shortest paths.
  • In an undirected graph, DFS edge classification has only tree edges and back edges when the graph is simple with no self-loops. There are no cross edges and no separate non-tree forward edges.
  • In an undirected BFS, for every edge (u,v)(u,v), the levels differ by at most one: ∣level(u)−level(v)∣≤1|level(u)-level(v)| \le 1. Equality is not guaranteed; a same-level edge such as one side of a triangle gives difference 00.
  • For a directed graph, CLRS-style DFS uses three colours: WHITE = unvisited, GRAY = discovered but not finished and active on the recursion stack, BLACK = finished.
  • Directed DFS edge (u,v)(u,v): if vv is WHITE it is a tree edge; if vv is GRAY it is a back edge; if vv is BLACK and d[u]<d[v]d[u]<d[v] it is a forward edge; if vv is BLACK and d[u]>d[v]d[u]>d[v] it is a cross edge. Here d[u]d[u] is discovery time.
  • Parenthesis theorem: DFS discovery and finish intervals [d[u],f[u]][d[u],f[u]] are either disjoint or one strictly contains the other. Partial overlap never occurs.
  • A DAG (Directed Acyclic Graph) has at least one topological ordering. A directed graph has a topological ordering if and only if it has no directed cycle.
  • A topological order lists vertices so that for every directed edge u→vu\to v, uu appears before vv.
  • A Strongly Connected Component (SCC) is a maximal set of vertices where every pair is mutually reachable. The component graph of SCCs of any directed graph is a DAG.
  • Kosaraju’s algorithm finds SCCs in two DFS passes: first on GG to get finishing order, then on the transpose GTG^T in decreasing finishing-time order.
  • BFS applications: shortest path in unweighted graphs, connected components, bipartite checking, level-order traversal, cycle detection in undirected graphs.
    DFS applications: topological sort, SCC, directed cycle detection, bridges/articulation points, maze and path problems.

How it works

BFS procedure

  1. Initialise every vertex as WHITE, with level ∞\infty and parent NIL.
  2. Mark source ss as GRAY, set level 00, enqueue ss.
  3. While the queue is not empty, dequeue uu.
  4. For each neighbour vv of uu: if vv is WHITE, mark it GRAY, set parent v=uv=u, set level v=level[u]+1v=level[u]+1, and enqueue vv.
  5. When all neighbours are processed, mark uu BLACK. The queue becomes empty after all reachable vertices are processed.
  6. For a disconnected graph, repeat BFS from every remaining WHITE vertex to get a BFS forest.

DFS procedure

  1. Initialise all vertices WHITE and time 00.
  2. For each WHITE vertex uu, call DFS-Visit(u)(u).
  3. In DFS-Visit: set colour of uu to GRAY; increment time; set d[u]=timed[u]=time.
  4. For each neighbour vv of uu: if WHITE, set parent v=uv=u and recurse; otherwise classify the edge.
  5. After all neighbours, set colour of uu to BLACK; increment time; set f[u]=timef[u]=time.

Topological sort using DFS

  1. Check that the graph is a DAG, or detect a back edge during DFS.
  2. Run DFS over all vertices.
  3. When a vertex finishes, push it onto the front of a list, or append it and reverse the list at the end.
  4. The resulting order is a topological order. Equivalently, output vertices in decreasing order of finishing time.

Kosaraju’s SCC algorithm

  1. Run DFS on the original graph GG; push each vertex onto a stack when it finishes.
  2. Build the transpose graph GTG^T by reversing every directed edge.
  3. Pop vertices from the stack. For each unvisited vertex, run DFS on GTG^T; every DFS tree obtained is one SCC.
  4. The vertices are processed in decreasing finishing-time order from the first pass.
Figure. It shows the queue loop: dequeue u, check each neighbour v, and enqueue unvisited neighbours after marking them visited with parent v = u and level u + 1. BFS ends when the queue is empty.

Formulas

  • Convention: G=(V,E)G=(V,E); ∣V∣|V| is number of vertices, ∣E∣|E| is number of edges. For an undirected graph, ∣E∣|E| counts each undirected edge once.

  • BFS or DFS time with adjacency list: T=Θ(∣V∣+∣E∣)T=\Theta(|V|+|E|).

  • BFS or DFS time with adjacency matrix: T=Θ(∣V∣2)T=\Theta(|V|^2).

  • BFS shortest-path property for reachable vv: level[v]=δ(s,v)level[v]=\delta(s,v), where δ(s,v)\delta(s,v) is the minimum number of edges from ss to vv.

  • Undirected BFS edge-level bound: ∣level(u)−level(v)∣≤1|level(u)-level(v)|\le 1.

  • Directed BFS edge u→vu\to v: level(v)≤level(u)+1level(v)\le level(u)+1.

  • DFS timestamps: 1≤d[u]<f[u]≤2∣V∣1\le d[u]<f[u]\le 2|V| when the global counter increments on each discovery and finish.

  • Parenthesis theorem: for any u,vu,v, the intervals [d[u],f[u]][d[u],f[u]] and [d[v],f[v]][d[v],f[v]] are disjoint or one contains the other.

  • Topological order property: for every edge u→vu\to v, order(u)<order(v)order(u)<order(v).

  • Kosaraju second-pass order: decreasing f[u]f[u] from the first DFS pass on GG.

Worked examples

Example 1: BFS levels and shortest path.
An undirected graph has vertices A,B,C,D,E,FA,B,C,D,E,F and edges AB,AC,BC,BD,CD,CE,DF,EFAB,AC,BC,BD,CD,CE,DF,EF. Run BFS from AA.
Start: AA level 00. Dequeue AA: discover B,CB,C at level 11. Dequeue BB: CC already visited, discover DD at level 22. Dequeue CC: BB visited, DD visited, discover EE at level 22. Dequeue DD: discover FF at level 33. Dequeue EE: FF already visited. Dequeue FF: done.
Levels: A=0,B=1,C=1,D=2,E=2,F=3A=0,B=1,C=1,D=2,E=2,F=3. Thus shortest AA to FF is 33 edges. Edge BCBC joins two level-11 vertices, so its level difference is 00, not 11.

Example 2: Directed DFS edge classification.
Let directed edges be A→BA\to B, B→DB\to D, D→AD\to A, A→DA\to D, A→CA\to C, C→DC\to D. Use adjacency order A:B,D,CA:B,D,C; B:DB:D; C:DC:D; D:AD:A.
DFS from AA: d[A]=1d[A]=1. A→BA\to B: BB WHITE, tree, d[B]=2d[B]=2. B→DB\to D: DD WHITE, tree, d[D]=3d[D]=3. D→AD\to A: AA GRAY, back. Finish DD at f[D]=4f[D]=4, finish BB at f[B]=5f[B]=5.
Back at AA, edge A→DA\to D: DD BLACK and d[A]=1<d[D]=3d[A]=1<d[D]=3, forward. A→CA\to C: CC WHITE, tree, d[C]=6d[C]=6. C→DC\to D: DD BLACK and d[C]=6>d[D]=3d[C]=6>d[D]=3, cross. Finish CC at f[C]=7f[C]=7, finish AA at f[A]=8f[A]=8.

EdgeColour of target when exploredClassification
A→BA\to BWHITETree
B→DB\to DWHITETree
D→AD\to AGRAYBack
A→DA\to DBLACK, d[A]<d[D]d[A]<d[D]Forward
A→CA\to CWHITETree
C→DC\to DBLACK, d[C]>d[D]d[C]>d[D]Cross

Example 3: Topological sort.
DAG vertices A,B,C,D,EA,B,C,D,E; edges A→B,A→C,B→D,C→D,D→EA\to B,A\to C,B\to D,C\to D,D\to E. DFS from AA, adjacency BB before CC. Finish order: E,D,B,C,AE,D,B,C,A. Decreasing finishing time gives A,C,B,D,EA,C,B,D,E. Check every edge: AA before BB and CC; BB before DD; CC before DD; DD before EE. Hence A,C,B,D,EA,C,B,D,E is a valid topological order.

Example 4: Kosaraju’s SCC algorithm.
Directed edges: A→BA\to B, B→AB\to A, B→CB\to C, C→DC\to D, D→CD\to C.
First DFS on GG from AA: finish order D,C,B,AD,C,B,A. Decreasing finish order: A,B,C,DA,B,C,D. Transpose GTG^T has edges B→AB\to A, A→BA\to B, C→BC\to B, D→CD\to C, C→DC\to D. Process AA in GTG^T: visits A,BA,B, so one SCC is {A,B}\{A,B\}.
Next unvisited is CC: visits C,DC,D, so the second SCC is {C,D}\{C,D\}. Thus SCCs are {A,B}\{A,B\} and {C,D}\{C,D\}, and the component graph is a DAG.

Example 5: Statement type.
Statement I: In any DFS of a directed graph, discovery and finish intervals of two vertices are either disjoint or one contains the other.
Statement II: If DFS classifies a directed edge (u,v)(u,v) as a cross edge, then vv is an ancestor of uu.
Statement I is true by the parenthesis theorem. Statement II is false: a cross edge goes to an already finished vertex that is neither an ancestor nor a descendant of uu. Hence I is true and II is false.

Comparison

FeatureBFSDFS
Data structureQueue, FIFOStack or recursion, LIFO
Exploration orderLevel by levelPath by path, deeper first
Shortest path in unweighted graphYes, gives minimum edge countNo, not generally
Time with adjacency listΘ(V+E)\Theta(V+E)Θ(V+E)\Theta(V+E)
Auxiliary spaceQueue up to O(V)O(V)Stack/recursion up to O(V)O(V)
Typical applicationsUnweighted shortest paths, bipartite test, connected componentsTopological sort, SCC, cycle detection, bridges
Directed DFS edge (u,v)(u,v)Condition when exploredMeaning
Treevv is WHITEDiscovery edge
Backvv is GRAYPoints to an ancestor; cycle in directed graph
Forwardvv is BLACK and d[u]<d[v]d[u]<d[v]Points to a descendant; not a tree edge
Crossvv is BLACK and d[u]>d[v]d[u]>d[v]Points to an already finished vertex in another branch

Revision summary

  • BFS uses a queue; DFS uses a stack or recursion.
  • Both BFS and DFS are Θ(V+E)\Theta(V+E) on adjacency lists; Θ(V2)\Theta(V^2) on adjacency matrices.
  • BFS tree depth equals shortest unweighted distance; DFS tree depth does not.
  • In a simple undirected graph, DFS has only tree and back edges.
  • In an undirected BFS, every edge joins equal-level or adjacent-level vertices; level difference is at most 11, not always exactly 11.
  • Directed DFS: WHITE target means tree; GRAY target means back; BLACK target is forward if d[u]<d[v]d[u]<d[v], cross if d[u]>d[v]d[u]>d[v].
  • Parenthesis theorem: DFS intervals are disjoint or nested, never partially overlapping.
  • Topological ordering exists iff the directed graph is a DAG.
  • DFS topological sort outputs decreasing finishing times; Kahn’s algorithm repeatedly removes indegree-zero vertices.
  • Kosaraju: first DFS on GG, second DFS on GTG^T in decreasing finish order; each second-pass DFS tree is an SCC.
  • The condensation graph of SCCs is always a DAG.

Previous-year exam insights

  • Undirected DFS questions often test the fact that no cross edge exists; check whether the graph is undirected before applying directed edge-type rules.
  • BFS depth statements are traps: in an undirected graph, an edge can join vertices at the same BFS level, so ∣i−j∣=1|i-j|=1 for every edge is false; only ∣i−j∣≤1|i-j|\le 1 is correct.
  • Complexity questions usually expect Θ(V+E)\Theta(V+E) for adjacency lists and Θ(V2)\Theta(V^2) for adjacency matrices, not O(E)O(E) alone.
  • Edge-classification questions require the CLRS colour rule: WHITE tree, GRAY back, BLACK forward or cross depending on discovery-time comparison.
  • Topological-sort questions test the exact condition: acyclic directed graph; DFS reverse finish order or Kahn indegree removal.
  • Kosaraju questions test the second-pass order: decreasing finishing time on the transpose graph, each DFS tree giving one SCC.
  • Assertion-reason questions often use the fact that the SCC component graph is a DAG, or that DFS intervals satisfy the parenthesis theorem.

Practice at PARIKSHA

You are ready for the PARIKSHA tests of this sub-topic when you can:

  • Define BFS and DFS and state their data structures and traversal orders.
  • Write the time and space complexities on adjacency lists and adjacency matrices.
  • Trace BFS on an unweighted graph and list levels and a shortest path.
  • Explain why an undirected DFS has no cross edges.
  • Classify every directed edge as tree, back, forward, or cross using colours and timestamps.
  • State and apply the DFS parenthesis theorem.
  • Produce a topological order using DFS finish times and using Kahn’s algorithm.
  • Run Kosaraju’s algorithm on a small directed graph and list all SCCs.
  • Identify the common trap in BFS level-difference statements for undirected graphs.

Attempt the Bfs Dfs And Their Applications sub-topic test first, then the Graph Algorithms Extras subject test.

Pages 1–2 of 2