DFS & Topological Ordering
We conclude with Depth-First Search (DFS) and its applications. DFS discovers the structure of a graph: back edges reveal cycles, DFS timestamps enable topological ordering of DAGs, and DFS forests reveal connected components.
Learning Objectives
Key Concepts
Depth-First Search
DFS explores a graph by going as deep as possible before backtracking. It assigns discovery time and finish time to each vertex, which encode the structure of the search.
Edge classification in directed graphs:
- -Tree edge: discovers a new vertex
- -Back edge: goes to an ancestor → indicates a cycle
- -Forward edge: goes to a descendant (non-tree)
- -Cross edge: goes to a vertex in a different subtree
- -
DFS runs in time
- -
A directed graph has a cycle iff DFS finds a back edge
- -
In undirected graphs, only tree and back edges exist
- -
Parenthesis property: and are either nested or disjoint
Topological Ordering
A topological ordering of a directed acyclic graph (DAG) is a linear ordering of vertices such that for every edge , comes before .
DFS gives a topological order: sort vertices by decreasing finish time .
- -
A DAG always has a topological ordering
- -
DFS finish times in reverse order give a topological ordering
- -
A directed graph is a DAG iff it has no back edges in DFS
- -
Applications: scheduling, dependency resolution, course prerequisites