Modified TopologicalSort().