Skip to content

topologicalSortDfs ​

topologicalSortDfs(graph) computes a topological ordering with depth-first traversal. It accepts an adjacency list or Graph<N, W> and returns absence if a back edge reveals a cycle.

SignatureReturnsComplexity
topologicalSortDfs(graph: usize[][])usize[]?O(V + E)
topologicalSortDfs(graph: Graph<N, W>)usize[]?O(V + E)

Every vertex appears once in the ordering. A graph with a directed cycle has no topological ordering and produces an empty optional result.

Example ​

tyrus
import { topologicalSortDfs } from "tyrus:algorithm";

const order: usize[]? = topologicalSortDfs([[1], []]);
if (order) {
    print(order[1]);  // 1
}

Study result ​

tyrus
interface TopologicalSortDfsInfo {
    order: usize[];
    processedVertexCount: usize;
    examinedEdgeCount: usize;
    cycleDetected: bool;
    finalStates: usize[];
    maxDepth: usize;
    backEdge: [usize, usize]?;
}
tyrus
import { TopologicalSortDfsInfo, TopologicalSortInfo, topologicalSortDfsInfo } from "tyrus:algorithm";
const info: TopologicalSortDfsInfo = topologicalSortDfsInfo([[1, 2], [3], [3], []]);
print(info.order); // [0, 2, 1, 3]
print(info.processedVertexCount); // 4
print(info.examinedEdgeCount); // 4
print(info.cycleDetected); // false
print(info.finalStates); // [2, 2, 2, 2]
print(info.maxDepth); // 3
print(info.backEdge ?? [9usize, 9usize]); // [9, 9]