diff --git a/dag.go b/dag.go index b83f805c..3946da71 100644 --- a/dag.go +++ b/dag.go @@ -84,10 +84,12 @@ func StableTopologicalSort[K comparable, T any](g Graph[K, T], less func(K, K) b } queue := make([]K, 0) + queued := make(map[K]struct{}) for vertex, predecessors := range predecessorMap { if len(predecessors) == 0 { queue = append(queue, vertex) + queued[vertex] = struct{}{} } } @@ -112,14 +114,21 @@ func StableTopologicalSort[K comparable, T any](g Graph[K, T], less func(K, K) b for vertex, predecessors := range predecessorMap { delete(predecessors, currentVertex) - if len(predecessors) == 0 { - queue = append(queue, vertex) + if len(predecessors) != 0 { + continue + } - sort.Slice(queue, func(i, j int) bool { - return less(queue[i], queue[j]) - }) + if _, ok := queued[vertex]; ok { + continue } + + queue = append(queue, vertex) + queued[vertex] = struct{}{} } + + sort.Slice(queue, func(i, j int) bool { + return less(queue[i], queue[j]) + }) } gOrder, err := g.Order()