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 . 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 contains the discovery edges. For every reachable vertex , its depth in the BFS tree equals the shortest unweighted path length from to .
- 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 , the levels differ by at most one: . Equality is not guaranteed; a same-level edge such as one side of a triangle gives difference .
- 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 : if is WHITE it is a tree edge; if is GRAY it is a back edge; if is BLACK and it is a forward edge; if is BLACK and it is a cross edge. Here is discovery time.
- Parenthesis theorem: DFS discovery and finish intervals 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 , appears before .
- 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 to get finishing order, then on the transpose 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
- Initialise every vertex as WHITE, with level and parent NIL.
- Mark source as GRAY, set level , enqueue .
- While the queue is not empty, dequeue .
- For each neighbour of : if is WHITE, mark it GRAY, set parent , set level , and enqueue .
- When all neighbours are processed, mark BLACK. The queue becomes empty after all reachable vertices are processed.
- For a disconnected graph, repeat BFS from every remaining WHITE vertex to get a BFS forest.
DFS procedure
- Initialise all vertices WHITE and time .
- For each WHITE vertex , call DFS-Visit.
- In DFS-Visit: set colour of to GRAY; increment time; set .
- For each neighbour of : if WHITE, set parent and recurse; otherwise classify the edge.
- After all neighbours, set colour of to BLACK; increment time; set .
Topological sort using DFS
- Check that the graph is a DAG, or detect a back edge during DFS.
- Run DFS over all vertices.
- When a vertex finishes, push it onto the front of a list, or append it and reverse the list at the end.
- The resulting order is a topological order. Equivalently, output vertices in decreasing order of finishing time.
Kosaraju’s SCC algorithm
- Run DFS on the original graph ; push each vertex onto a stack when it finishes.
- Build the transpose graph by reversing every directed edge.
- Pop vertices from the stack. For each unvisited vertex, run DFS on ; every DFS tree obtained is one SCC.
- The vertices are processed in decreasing finishing-time order from the first pass.
Drawing the diagram…
Formulas
-
Convention: ; is number of vertices, is number of edges. For an undirected graph, counts each undirected edge once.
-
BFS or DFS time with adjacency list: .
-
BFS or DFS time with adjacency matrix: .
-
BFS shortest-path property for reachable : , where is the minimum number of edges from to .
-
Undirected BFS edge-level bound: .
-
Directed BFS edge : .
-
DFS timestamps: when the global counter increments on each discovery and finish.
-
Parenthesis theorem: for any , the intervals and are disjoint or one contains the other.
-
Topological order property: for every edge , .
-
Kosaraju second-pass order: decreasing from the first DFS pass on .
Worked examples
Example 1: BFS levels and shortest path.
An undirected graph has vertices and edges . Run BFS from .
Start: level . Dequeue : discover at level . Dequeue : already visited, discover at level . Dequeue : visited, visited, discover at level . Dequeue : discover at level . Dequeue : already visited. Dequeue : done.
Levels: . Thus shortest to is edges. Edge joins two level- vertices, so its level difference is , not .
Example 2: Directed DFS edge classification.
Let directed edges be , , , , , . Use adjacency order ; ; ; .
DFS from : . : WHITE, tree, . : WHITE, tree, . : GRAY, back. Finish at , finish at .
Back at , edge : BLACK and , forward. : WHITE, tree, . : BLACK and , cross. Finish at , finish at .
| Edge | Colour of target when explored | Classification |
|---|---|---|
| WHITE | Tree | |
| WHITE | Tree | |
| GRAY | Back | |
| BLACK, | Forward | |
| WHITE | Tree | |
| BLACK, | Cross |
Example 3: Topological sort.
DAG vertices ; edges . DFS from , adjacency before . Finish order: . Decreasing finishing time gives . Check every edge: before and ; before ; before ; before . Hence is a valid topological order.
Example 4: Kosaraju’s SCC algorithm.
Directed edges: , , , , .
First DFS on from : finish order . Decreasing finish order: . Transpose has edges , , , , . Process in : visits , so one SCC is .
Next unvisited is : visits , so the second SCC is . Thus SCCs are and , 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 as a cross edge, then is an ancestor of .
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 . Hence I is true and II is false.
Comparison
| Feature | BFS | DFS |
|---|---|---|
| Data structure | Queue, FIFO | Stack or recursion, LIFO |
| Exploration order | Level by level | Path by path, deeper first |
| Shortest path in unweighted graph | Yes, gives minimum edge count | No, not generally |
| Time with adjacency list | ||
| Auxiliary space | Queue up to | Stack/recursion up to |
| Typical applications | Unweighted shortest paths, bipartite test, connected components | Topological sort, SCC, cycle detection, bridges |
| Directed DFS edge | Condition when explored | Meaning |
|---|---|---|
| Tree | is WHITE | Discovery edge |
| Back | is GRAY | Points to an ancestor; cycle in directed graph |
| Forward | is BLACK and | Points to a descendant; not a tree edge |
| Cross | is BLACK and | 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 on adjacency lists; 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 , not always exactly .
- Directed DFS: WHITE target means tree; GRAY target means back; BLACK target is forward if , cross if .
- 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 , second DFS on 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 for every edge is false; only is correct.
- Complexity questions usually expect for adjacency lists and for adjacency matrices, not 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.