DFS & Topological Sort
Depth-first search (DFS)
Follow one path as deep as possible, then back up and try the next. Implement it with recursion or an explicit stack. O(V + E) time.
What DFS is great at
- Connected components and counting islands
- Cycle detection
- Path existence ("can I get from A to B?")
- Topological sort
- Backtracking puzzles (mazes, Sudoku)
BFS vs DFS
| BFS | DFS | |
|---|---|---|
| Structure | queue | stack / recursion |
| Shortest path (unweighted) | ✅ | ❌ |
| Memory | wide graphs use a lot | proportional to depth |
| Natural for | levels, nearest | paths, cycles, ordering |
Topological sort
Order the tasks of a directed acyclic graph (DAG) so every task comes after its prerequisites: course schedules, build systems, spreadsheet formulas.
Kahn's algorithm (BFS style):
- Count incoming edges (in-degree) for each node.
- Queue every node with in-degree 0.
- Pop a node, add it to the order, and lower its neighbours' in-degrees, queueing any that reach 0.
- If the order doesn't include every node, there's a cycle, so no valid order exists.
Cycle detection in directed graphs
DFS with three colours: unvisited, in progress, done. Reaching an "in progress" node means you found a cycle.
Example
from collections import deque
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": [], "E": ["F"], "F": []}
def dfs(node, seen=None):
seen = set() if seen is None else seen
seen.add(node)
order = [node]
for nxt in graph[node]:
if nxt not in seen:
order += dfs(nxt, seen)
return order
def count_components(g):
undirected = {n: set() for n in g}
for a, outs in g.items():
for b in outs:
undirected[a].add(b); undirected[b].add(a)
seen, count = set(), 0
for n in undirected:
if n not in seen:
count += 1
stack = [n]
while stack:
cur = stack.pop()
if cur not in seen:
seen.add(cur)
stack.extend(undirected[cur] - seen)
return count
def topo_sort(courses, prereqs): # prereqs: (before, after)
out = {c: [] for c in courses}
indeg = {c: 0 for c in courses}
for before, after in prereqs:
out[before].append(after)
indeg[after] += 1
q = deque(c for c in courses if indeg[c] == 0)
order = []
while q:
c = q.popleft()
order.append(c)
for nxt in out[c]:
indeg[nxt] -= 1
if indeg[nxt] == 0:
q.append(nxt)
return order if len(order) == len(courses) else None # None = cycle
print(dfs("A")) # ['A', 'B', 'D', 'C']
print(count_components(graph)) # 2
print(topo_sort(["Math", "Physics", "Robotics"],
[("Math", "Physics"), ("Physics", "Robotics")]))
# ['Math', 'Physics', 'Robotics']
print(topo_sort(["X", "Y"], [("X", "Y"), ("Y", "X")])) # None (cycle)