7. DFS and Topological Sorting
Visit(E, u):
pre[u] <- T; T <- T+1
visited[u] <- True
FOR v in edges[u]:
IF not visited[v]:
Visit(v)
post[u] <- T; T <- T+1
DFS(G):
T <- 1 # Counter
visited <- [False] * |V|
FOR u in V:
IF not visited[u]:
Visit(u)
pre: when entered nodes
post: when left nodes
Example pre- and post-order intervals:

Reverse post ordering is topological sort since all the nodes it depends on have been called before.
Note: If we’re only interested in the topological sort, we don’t have to track pre- and post-orderings. We can simply append the node to the topological sort at the point where we set the post order and then reverse the array at the very end.
Edge Types
Given an edge , there are 4 different types of edges:
| Type | Pre/Post | Description |
|---|---|---|
| Tree edge | Edge traversed by DFS | |
| Forward edge | is a descendant of , but it was already visited through an intermediary descendent of | |
| Back edge | is a descendant of , and the edge goes back to an ancestor cycle b/c we can travel from to and back again. | |
| Cross edge | already visited in different DFS subtree. |
is impossible b/c would already be visited in ‘s recursive call. Overlapping but not nested intervals are impossible due to the recursive nature of DFS.