The proof suggests the following high-level algorithm to topologically sort a dag \(G\).
H := G
repeat until H has no vertices {
"grow" a dfs path P till a sink s is found
T[s] ← n
n ← n - 1
delete s from P & H
}
When the algorithm ends, \(T[1..n]\) gives the topological numbering.
Low-level algorithm:
top(G) {
num ← n
for each vertex v do {
T[v] ← 0
}
for each vertex v do {
if T[v] = 0 then dfs(v)
}
}
dfs(v) {
for each edge (v,w) do {
if T[w] = 0 then dfs(w)
}
/* v is now a sink in the high level algorithm */
T[v] ← num
num ← num - 1
}
We calculate the values specified by the formula by modifying the dfs code as follows.
longest(G) {
for each vertex v do {
d[v] ← -1
}
for each vertex v do {
if d[v] = -1 then dfs(v)
}
}
dfs(v) {
d[v] ← 0
for each edge (v,w) do {
if d[w] = -1 then dfs(w)
d[v] ← max { d[v], l[v,w] + d[w] }
}
}