topologicalSortKahn
topologicalSortKahn(graph) returns a topological ordering for a directed acyclic graph. It accepts an adjacency list or Graph<N, W> and returns absence when a cycle prevents a complete ordering.
| Signature | Returns | Complexity |
|---|---|---|
topologicalSortKahn(graph: usize[][]) | usize[]? | O(V + E) |
topologicalSortKahn(graph: Graph<N, W>) | usize[]? | O(V + E) |
The result contains each vertex once. An empty optional result means that the input contains a directed cycle.
Example
tyrus
import { topologicalSortKahn } from "tyrus:algorithm";
const order: usize[]? = topologicalSortKahn([[1], []]);
if (order) {
print(order[0]); // 0
}Study result
tyrus
interface TopologicalSortKahnInfo {
order: usize[];
processedVertexCount: usize;
examinedEdgeCount: usize;
cycleDetected: bool;
initialIndegrees: usize[];
indegreeDecrementCount: usize;
maxQueueSize: usize;
}tyrus
import { TopologicalSortInfo, TopologicalSortKahnInfo, topologicalSortKahnInfo } from "tyrus:algorithm";
const info: TopologicalSortKahnInfo = topologicalSortKahnInfo([[1, 2], [3], [3], []]);
print(info.order); // [0, 1, 2, 3]
print(info.processedVertexCount); // 4
print(info.examinedEdgeCount); // 4
print(info.cycleDetected); // false
print(info.initialIndegrees); // [0, 1, 1, 2]
print(info.indegreeDecrementCount); // 4
print(info.maxQueueSize); // 2