Reputation: 5827
Is there an algorithm that, given an unweighted directed acyclic graph, sorts all nodes into a list of sets of nodes such that
u->v
, v
occurs in a set further down the list than u
) andIs there a name for this problem?
A possible sort for the graph below would be
[1], [2, 3], [4, 5], [6, 7]
An alternative solution would be
[1], [2, 3], [4], [5, 6, 7]
Upvotes: 3
Views: 900
Reputation: 1118
Consider this variation of the canonical Kahn's algorithm:
Starting with n = 0:
The list of S_0 ... S_k
sets contains the result.
Upvotes: 3
Reputation: 65508
Define the stage index of each node to be zero if it has no predecessors, or one plus the max stage index of its predecessors. Put each node in the indicated stage.
The stage indices can be evaluated efficiently in topological order, making this an easy extension to your favorite topological sorting algorithm.
Upvotes: 2