> [[Graph traversal]] that orders the [[Node|vertices]] of a [[Directed acyclic graph|DAG]] so each comes before every [[Node|vertex]] it points at - an [[Edge|edge]] `A -> B` reads "A must come before B".[^1]
## Takes
- the [[Node|vertices]], in order
- the directed [[Edge|edges]], each `(from, to)`, in order
A [[Graph|graph]] usually admits many such orders. Both input orders pin this one: the [[Depth First Order#Reverse post|reverse post-order]] of a [[Depth First Search|depth-first walk]] started from each [[Node|vertex]] in turn, following each [[Node|vertex's]] [[Edge|edges]] in the order given.
## Returns
- the order - every [[Node|vertex]] once, each before every [[Node|vertex]] it points at
- nothing, when the [[Graph|graph]] has a [[Cycles|cycle]] - no such order exists there
## Depends on
- [[Cycles]] - whether the [[Graph|graph]] has a [[Cycles|cycle]]
- [[Depth First Order#Reverse post]] - the order
## Pseudocode
```
topological(vertices, edges)
if cycles(vertices, edges) is nothing
return reversePost(depthFirstOrder(vertices, edges))
return nothing
```
## Examples
| graph | returns |
| --- | --- |
| `1 -> 2`, `2 -> 3` | `1 2 3` |
| [[tinyGraph]] | `8 7 6 9 11 10 12 2 3 0 5 4 1` |
| [[tinyGraph]] and `4 -> 2` | nothing - `2 -> 3 -> 5 -> 4 -> 2` is a [[Cycles\|cycle]] |
[^1]: https://en.wikipedia.org/wiki/Topological_sorting