Simplify topological sort with one set of nested loops