Depth-First Search: Lecture Overview
Depth-First Search: Lecture Overview
Lecture Overview
Depth-First Search
Edge Classification
Cycle Testing
Topological Sort
Recall:
graph search: explore a graph
e.g., find a path from start vertex s to a desired vertex
adjacency lists: array Adj of |V | linked lists
for each vertex u V , Adj[u] stores us neighbors, i.e., {v V | (u, v) E}
(just outgoing edges if directed)
For example:
b
Adj
search from
start vertex s
(only see
stuff reachable
from s)
explore
entire graph
(could do same
to extend BFS)
Example
S1
forward
edge
back
edge
cross edge
S2
6
back edge
Figure 4: Depth-First Traversal
Edge Classification
Analysis
DFS-visit gets called withX
a vertex s only once (because then parent[s] set)
= time in DFS-visit =
|Adj[s]| = O(E)
sV
Cycle Detection
Graph G has a cycle DFS has a back edge
Proof
(<=)
tree edges
is a cycle
v0
FIRST!
Job scheduling
Given Directed Acylic Graph (DAG), where vertices represent tasks & edges represent
dependencies, order tasks without violating dependencies
8
G
4
A
E
6
Source:
Source = vertex with no incoming edges
= schedulable at beginning (A,G,I)
Attempt:
BFS from each source:
from A finds A, BH, C, F
from D finds D, BE, CF slow . . . and wrong!
from G finds G, H
from I finds I
Topological Sort
DFS-Visit(v)
...
order.append(v)
order.reverse()
Correctness
For any edge (u, v) u ordered before v, i.e., v finished before u
if u visited before v:
before visit to u finishes, will visit v (via (u, v) or otherwise)
= v finishes before u
if v visited before u:
graph is acyclic
= u cannot be reached from v
= visit to v finishes before visiting u