Depth-First Search
🌲 Graph Search: Depth-First Search (DFS)
This document provides a comprehensive overview of Depth-First Search (DFS), a fundamental graph traversal algorithm. We will cover its implementation, running time, edge classification, and key applications such as cycle detection and topological sorting.
📚 Introduction to Depth-First Search (DFS)
Depth-First Search (DFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the root (or an arbitrary node) and explores as far as possible along each branch before backtracking. It's conceptually similar to solving a maze.
Input: Graphs are typically specified using an adjacency list, where each vertex has a list of vertices it is connected to by an edge.
Goal: To explore the graph by visiting all vertices, ensuring each vertex is visited only once.
Comparison with BFS:
Breadth-First Search (BFS) explores layer by layer, finding shortest paths from a source vertex
sto all reachable vertices. It's also good for detecting unreachable vertices.DFS explores deeply before backtracking. While it can also detect unreachable vertices, it's often used to explore the entire graph, not just the component reachable from
s.
🌲 Maze Solving Analogy
Imagine solving a maze:
You go as far as you can down one path.
If you hit a dead end, you backtrack to the last junction where you had other choices.
To avoid getting lost, you might leave "breadcrumbs" or mark visited paths.
On a computer, this backtracking and exploration is efficiently handled using recursion.
📝 DFS Algorithm Implementation
DFS is a remarkably simple algorithm, often implemented with just a few lines of code. It primarily relies on recursion and a mechanism to track visited nodes.
🔍 DFS_Visit(s, adj, parent)
This is the recursive core of DFS, visiting all vertices reachable from a given source s.
DFS_Visit(s, adj, parent):
# Mark 's' as visited by giving it a parent (e.g., None for the start node)
# parent[s] = some_value (e.g., None or the node that led to s)
for v in adj[s]: # Iterate over all outgoing edges from s
if v not in parent: # If v has not been visited yet
parent[v] = s # Mark v as visited, setting its parent to s
DFS_Visit(v, adj, parent) # Recursively visit vKey Points:
parentDictionary: This dictionary stores the parent of each visited node. Its primary role is to act as a set of visited nodes. Ifvis inparent, it meansvhas already been visited.No Repetition: The
if v not in parent:check is crucial. It ensures that each vertex is visited at most once, preventing infinite loops in graphs with cycles.
🌐 DFS(V, adj): Exploring the Entire Graph
The DFS_Visit function only explores the connected component reachable from its starting node s. To explore the entire graph, especially if it's disconnected, a top-level DFS function is used.
DFS(V, adj):
parent = {} # Initialize an empty dictionary to track visited nodes (and their parents)
for s in V: # Iterate over all vertices in the graph
if s not in parent: # If s has not been visited yet (i.e., it's part of a new component)
parent[s] = None # Mark s as visited (it's a root of a new DFS tree)
DFS_Visit(s, adj, parent) # Start a new DFS traversal from sHow it works:
It iterates through all vertices
sin the graphV.If
shas not been visited (i.e.,sis not in theparentdictionary), it meanssis the root of a new connected component that hasn't been explored yet.A new
DFS_Visitis initiated froms, exploring everything reachable from it.Vertices already visited (as part of previous
DFS_Visitcalls from other components) are simply skipped.
📊 Example Walkthrough
Let's trace DFS on a sample directed graph: (Imagine a graph with nodes a, b, c, d, e, f and directed edges: a->b, a->d, b->e, e->d, c->e, c->f, f->f)
Assume vertices are processed alphabetically (a, b, c, d, e, f).
DFS(a): (Outer loop starts withs = a)parent[a] = None(markavisited)DFS_Visit(a):Consider
a -> b:bnot visited.parent[b] = a.DFS_Visit(b)Consider
b -> e:enot visited.parent[e] = b.DFS_Visit(e)Consider
e -> d:dnot visited.parent[d] = e.DFS_Visit(d)Consider
d -> b:balready visited. Skip.DFS_Visit(d)finishes. Returns.
DFS_Visit(e)finishes. Returns.
DFS_Visit(b)finishes. Returns.
Consider
a -> d:dalready visited. Skip.DFS_Visit(a)finishes. Returns.
DFS(b): (Outer loop moves tos = b)balready visited. Skip.
DFS(c): (Outer loop moves tos = c)cnot visited.parent[c] = None(markcvisited)DFS_Visit(c):Consider
c -> f:fnot visited.parent[f] = c.DFS_Visit(f)Consider
f -> f:falready visited. Skip.DFS_Visit(f)finishes. Returns.
Consider
c -> e:ealready visited. Skip.DFS_Visit(c)finishes. Returns.
DFS(d, e, f): (Outer loop moves throughd,e,f)All are already visited. Skip.
The DFS traversal explores the entire graph, potentially starting multiple DFS_Visit calls for disconnected components.
⏱️ Running Time Analysis
The running time of DFS is linear with respect to the size of the graph.
Θ(V+E): This is considered linear time because
V + Erepresents the total size of the input (number of vertices and edges).
Breakdown:
Outer
DFSLoop: Thefor s in Vloop iterates|V|times. For eachs, theif s not in parentcheck andparent[s] = Noneoperation take constant time. So, this part contributes Θ(V).DFS_VisitCalls:Each vertex
vis an argument toDFS_Visitat most once. This is guaranteed by theif v not in parent:check before making a recursive call.Inside
DFS_Visit(s), thefor v in adj[s]loop iterates over all outgoing edges froms. The cost for this loop is proportional todegree(s).Summing the work done across all
DFS_Visitcalls: ∑v∈Vdegree(v). For a directed graph, this sum is exactly|E|(number of edges). For an undirected graph, it's2|E|.Therefore, the total work from
DFS_Visitcalls contributes Θ(E).
Total Running Time: Θ(V)+Θ(E)=Θ(V+E).
🌳 Edge Classification in DFS
During a DFS traversal, every edge in the graph is visited and can be classified into one of several types based on its relationship to the DFS tree (or forest). This classification is particularly useful for understanding graph properties.
We need to track start times and finish times for each vertex.
Start Time (
d[u]): The time whenDFS_Visit(u)is first called.Finish Time (
f[u]): The time whenDFS_Visit(u)finishes (i.e., returns).A global counter increments with each "step" (e.g., calling
DFS_Visit, iterating an edge, finishingDFS_Visit).
categorizing Edges
For an edge (u,v):
🌲 Tree Edges (Bold in example):
An edge (u,v) is a tree edge if
vis unvisited whenDFS_Visit(u)explores (u,v).These edges form the DFS forest (a set of DFS trees). The
parentpointers directly represent the reverse of tree edges.Example:
a -> b,b -> e,e -> d,c -> f.
➡️ Forward Edges:
An edge (u,v) is a forward edge if
vis already visited whenDFS_Visit(u)explores (u,v), andd[u] < d[v]andf[v] < f[u].This means
vis a descendant ofuin the DFS tree, but (u,v) is not a tree edge (it was skipped becausevwas already visited by some other path fromu).Example:
a -> d(in our example,dis a descendant ofathrougha->b->e->d).
⬅️ Back Edges:
An edge (u,v) is a back edge if
vis already visited whenDFS_Visit(u)explores (u,v), andd[v] < d[u]andf[u] < f[v].This means
vis an ancestor ofuin the DFS tree. WhenDFS_Visit(u)is active,vis currently on the recursion stack.Example:
d -> b(b is an ancestor of d:b->e->d).f -> f(f is an ancestor of f, a self-loop).
↔️ Cross Edges:
An edge (u,v) is a cross edge if
vis already visited whenDFS_Visit(u)explores (u,v), andf[v] < d[u].This means
vhas already been completely finished (itsDFS_Visitcall has returned) by the timeuis being explored.uandvare not ancestor-descendant related.Example:
c -> e(e was finished before c was even started in its component).
🧐 Edge Classification in Undirected Graphs
A common point of confusion is how edge types manifest in undirected graphs.
🌲 Tree Edges: Always exist.
⬅️ Back Edges: Always exist. Any non-tree edge in an undirected graph will be a back edge.
❌ Forward Edges: Do not exist in undirected graphs. If an edge (u,v) could be a forward edge (meaning
vis a descendant ofuandvwas visited via another path fromu), then the edge (v,u) would be explored whenDFS_Visit(v)is active. Sinceuis an ancestor, this would be classified as a back edge.❌ Cross Edges: Do not exist in undirected graphs. Similar to forward edges, if a cross edge existed, it would imply a path between two nodes not in an ancestor-descendant relationship. Because the graph is undirected, the edge could be traversed in either direction, and one of the nodes would eventually be visited as a descendant, leading to a back edge.
In undirected graphs, all edges are either tree edges or back edges.
🔄 Application 1: Cycle Detection
One of the most powerful applications of DFS is detecting cycles in a graph.
A directed graph
Ghas a cycle if and only if a Depth-First Search ofGyields a back edge.
This theorem holds for both directed and undirected graphs.
➡️ Proof: If a Back Edge Exists, then a Cycle Exists
Premise: Assume there is a back edge (u,v).
Definition of Back Edge: By definition, if (u,v) is a back edge, then
vis an ancestor ofuin the DFS tree.Path in DFS Tree: This means there is a directed path of tree edges from
vtou. Let this path be v⇝u.Cycle Formation: Combining the path v⇝u with the back edge (u,v) creates a cycle: v⇝u→v.
Conclusion: Therefore, if a back edge exists, a cycle exists.
⬅️ Proof: If a Cycle Exists, then a Back Edge Exists
Premise: Assume there is a cycle C=(v0→v1→⋯→vk→v0) in the graph.
First Visited Vertex: Let v0 be the first vertex in the cycle C that is visited by
DFS_Visit. (If another vertex vi is visited first, we can relabel it as v0 without loss of generality).DFS Traversal: Since v0 is the first vertex in C to be visited, all other vertices v1,…,vk in the cycle are unvisited when
DFS_Visit(v_0)begins.Reachability: Because v0→v1→⋯→vk is a path, all vertices v1,…,vk are reachable from v0.
Depth-First Property: Due to the depth-first nature of DFS,
DFS_Visit(v_0)will explore all reachable unvisited nodes. This meansDFS_Visit(v_1), \dots, DFS_Visit(v_k)will all be called beforeDFS_Visit(v_0)finishes.Recursion Stack: Consequently, when
DFS_Visit(v_k)is active,v_0, v_1, \dots, v_kwill all be on the recursion stack (meaning they are "in process").Considering Edge (vk,v0): When
DFS_Visit(v_k)explores the edge (vk,v0):v_0is already visited (it was the first in the cycle).v_0is currently on the recursion stack (it hasn't finished yet).This precisely matches the definition of a back edge.
Conclusion: Therefore, if a cycle exists, a back edge must exist.
Algorithm for Cycle Detection:
Run the full
DFSalgorithm on the graph.During the traversal, identify back edges using the start/finish times or by checking if
vis currently "in process" (on the recursion stack) when exploring an edge (u,v).If any back edge is found, the graph has a cycle. If no back edges are found, the graph is acyclic.
This algorithm runs in linear time Θ(V+E) because it's essentially a DFS.
🗓️ Application 2: Topological Sort
Topological sort is used to find a linear ordering of vertices in a Directed Acyclic Graph (DAG) such that for every directed edge (u,v), vertex u comes before vertex v in the ordering. This is often used for job scheduling or dependency resolution.
Input: A Directed Acyclic Graph (DAG). (If the graph has cycles, topological sort is impossible).
Goal: To produce a linear ordering of all vertices such that if there is an edge u→v, then
uappears beforevin the ordering.
💼 Job Scheduling Example
Imagine a set of tasks where some tasks must be completed before others.
Vertices: Represent tasks (e.g., "put on socks", "put on shoes").
Edges: Represent dependencies (e.g., "put on socks" → "put on shoes" means socks must be on before shoes).
A topological sort provides a valid sequence to perform these tasks.
🧠 Algorithm for Topological Sort
Run the full
DFSalgorithm on the DAG.As each vertex finishes (i.e., its
DFS_Visitcall returns), add it to the front of a linked list (or push it onto a stack).The final list (or stack contents, popped in order) represents a topological sort of the graph. This is equivalent to outputting the reverse of the finishing times of the vertices.
👨🏫 Proof of Correctness
We need to prove that for any edge (u,v) in the DAG, u appears before v in the topological sort. This means u must have a later finishing time than v (i.e., f[v] < f[u]).
Since the graph is a DAG, we know there are no back edges. So, for any edge (u,v), it can only be a tree edge, a forward edge, or a cross edge.
We consider two cases for the start times of u and v:
Case 1: u starts before v (d[u] < d[v])
When
DFS_Visit(u)is called,vis unvisited.Since there is an edge u→v,
vis reachable fromu.Due to the depth-first nature,
DFS_Visit(u)will explorev(either directly via u→v as a tree edge, or through some path u⇝v).This means
DFS_Visit(v)will be called and complete beforeDFS_Visit(u)finishes.Therefore,
f[v] < f[u]. This is the desired outcome:vfinishes beforeu, soucomes beforevin the reversed finishing order.
Case 2: v starts before u (d[v] < d[u])
When
DFS_Visit(v)is called,uis unvisited.We have an edge u→v.
If
DFS_Visit(v)were to exploreu(meaning v⇝u), then given the edge u→v, we would have a cycle v⇝u→v.However, the graph is a DAG, so no cycles exist.
Therefore,
DFS_Visit(v)cannot reachu.umust remain unvisited untilDFS_Visit(v)completely finishes.This implies that
DFS_Visit(v)finishes beforeDFS_Visit(u)even begins.Therefore,
f[v] < d[u] < f[u]. This again meansf[v] < f[u], which is the desired outcome.
Conclusion: In both cases, for any edge (u,v), v finishes before u. Thus, when we reverse the order of finishing times, u will always appear before v, yielding a valid topological sort.
Running Time: Like DFS, topological sort runs in linear time Θ(V+E).

Ask anything
We've read this whole study set, so questions about it get the best answers.