Sub topic 2
Why DFS Runs in O(V + E)
This chapter assumes you can already write recursive DFS over an adjacency list, and that you know Big-O notation and the difference between directed and undirected graphs.
Why DFS Runs in O(V + E)
The visited check means visit runs at most once per vertex, which accounts for O(V). Each call loops over that vertex's adjacency list one time. Every edge therefore gets examined once in a directed graph and twice in an undirected graph, which accounts for O(E). The total is O(V + E). With an adjacency matrix, finding a vertex's neighbors means scanning a whole row, so the cost rises to O(V²).
Extra space is O(V) for the visited set plus the recursion stack. On a long path the stack can be V frames deep, which can exceed Python's default recursion limit.
Visiting Every Vertex: The DFS Forest
A single call to visit reaches only the vertices reachable from its start. To cover the whole graph, loop over every vertex and launch a new DFS from each one that is still unvisited. Each launch builds one tree, and the trees together form the DFS forest.
Discovery and Finish Times
Keep a counter. Stamp a vertex's discovery time when you enter it and its finish time after all its neighbors are done.
def dfs_times(graph):
time = 0
disc, fin = {}, {}
def visit(u):
nonlocal time
time += 1
disc[u] = time
for v in graph[u]:
if v not in disc:
visit(v)
time += 1
fin[u] = time
for u in graph:
if u not in disc:
visit(u)
return disc, fin
graph = {"A": ["B"], "B": ["C"], "C": ["A"], "D": ["C"]}
disc, fin = dfs_times(graph)
print(disc) # {'A': 1, 'B': 2, 'C': 3, 'D': 7}
print(fin) # {'C': 4, 'B': 5, 'A': 6, 'D': 8}Classifying Edges During DFS
When you examine an edge u→v, the state of v tells you the edge's type. A vertex is white if it is undiscovered, gray if it has been discovered but not finished, and black if it has finished.
| Edge type | Condition on v | Example above |
|---|---|---|
| Tree | white | A→B, B→C |
| Back | gray (an ancestor of u) | C→A |
| Forward | black, disc[u] < disc[v] | none |
| Cross | black, disc[v] < disc[u] | D→C |
Detecting Cycles
A directed graph has a cycle exactly when DFS finds a back edge:
WHITE, GRAY, BLACK = 0, 1, 2
def has_cycle(graph):
color = {node: WHITE for node in graph}
def visit(node):
color[node] = GRAY
for neighbor in graph[node]:
if color[neighbor] == GRAY:
return True # back edge: cycle found
if color[neighbor] == WHITE and visit(neighbor):
return True
color[node] = BLACK
return False
return any(color[node] == WHITE and visit(node) for node in graph)
print(has_cycle({"a": ["b"], "b": ["c"], "c": ["a"]})) # True
print(has_cycle({"a": ["b"], "b": ["c"], "c": []})) # FalseExercise
In the dfs_times example, why is D→C a cross edge and not a back edge?
Show answer
When DFS examines D→C, C is already black (it finished at time 4) and was discovered before D (3 < 7). A back edge requires C to be gray, still on the current path, so D→C does not close a cycle.