Debian Codegraph @

dag.go

raw symbols SCIP
1 package graph
2
3 import (
4 "errors"
5 "fmt"
6 "sort"
7 )
8
9 // TopologicalSort runs a topological sort on a given directed graph and returns
10 // the vertex hashes in topological order. The topological order is a non-unique
11 // order of vertices in a directed graph where an edge from vertex A to vertex B
12 // implies that vertex A appears before vertex B.
13 //
14 // Note that TopologicalSort doesn't make any guarantees about the order. If there
15 // are multiple valid topological orderings, an arbitrary one will be returned.
16 // To make the output deterministic, use [StableTopologicalSort].
17 //
18 // TopologicalSort only works for directed acyclic graphs. This implementation
19 // works non-recursively and utilizes Kahn's algorithm.
20 func TopologicalSort[K comparable, T any](g Graph[K, T]) ([]K, error) {
21 if !g.Traits().IsDirected {
22 return nil, fmt.Errorf("topological sort cannot be computed on undirected graph")
23 }
24
25 gOrder, err := g.Order()
26 if err != nil {
27 return nil, fmt.Errorf("failed to get graph order: %w", err)
28 }
29
30 predecessorMap, err := g.PredecessorMap()
31 if err != nil {
32 return nil, fmt.Errorf("failed to get predecessor map: %w", err)
33 }
34
35 queue := make([]K, 0)
36
37 for vertex, predecessors := range predecessorMap {
38 if len(predecessors) == 0 {
39 queue = append(queue, vertex)
40 }
41 }
42
43 order := make([]K, 0, gOrder)
44 visited := make(map[K]struct{}, gOrder)
45
46 for len(queue) > 0 {
47 currentVertex := queue[0]
48 queue = queue[1:]
49
50 if _, ok := visited[currentVertex]; ok {
51 continue
52 }
53
54 order = append(order, currentVertex)
55 visited[currentVertex] = struct{}{}
56
57 for vertex, predecessors := range predecessorMap {
58 delete(predecessors, currentVertex)
59
60 if len(predecessors) == 0 {
61 queue = append(queue, vertex)
62 }
63 }
64 }
65
66 if len(order) != gOrder {
67 return nil, errors.New("topological sort cannot be computed on graph with cycles")
68 }
69
70 return order, nil
71 }
72
73 // StableTopologicalSort does the same as [TopologicalSort], but takes a function
74 // for comparing (and then ordering) two given vertices. This allows for a stable
75 // and deterministic output even for graphs with multiple topological orderings.
76 func StableTopologicalSort[K comparable, T any](g Graph[K, T], less func(K, K) bool) ([]K, error) {
77 if !g.Traits().IsDirected {
78 return nil, fmt.Errorf("topological sort cannot be computed on undirected graph")
79 }
80
81 predecessorMap, err := g.PredecessorMap()
82 if err != nil {
83 return nil, fmt.Errorf("failed to get predecessor map: %w", err)
84 }
85
86 queue := make([]K, 0)
87 queued := make(map[K]struct{})
88
89 for vertex, predecessors := range predecessorMap {
90 if len(predecessors) == 0 {
91 queue = append(queue, vertex)
92 queued[vertex] = struct{}{}
93 }
94 }
95
96 order := make([]K, 0, len(predecessorMap))
97 visited := make(map[K]struct{})
98
99 sort.Slice(queue, func(i, j int) bool {
100 return less(queue[i], queue[j])
101 })
102
103 for len(queue) > 0 {
104 currentVertex := queue[0]
105 queue = queue[1:]
106
107 if _, ok := visited[currentVertex]; ok {
108 continue
109 }
110
111 order = append(order, currentVertex)
112 visited[currentVertex] = struct{}{}
113
114 frontier := make([]K, 0)
115
116 for vertex, predecessors := range predecessorMap {
117 delete(predecessors, currentVertex)
118
119 if len(predecessors) != 0 {
120 continue
121 }
122
123 if _, ok := queued[vertex]; ok {
124 continue
125 }
126
127 frontier = append(frontier, vertex)
128 queued[vertex] = struct{}{}
129 }
130
131 sort.Slice(frontier, func(i, j int) bool {
132 return less(frontier[i], frontier[j])
133 })
134
135 queue = append(queue, frontier...)
136 }
137
138 gOrder, err := g.Order()
139 if err != nil {
140 return nil, fmt.Errorf("failed to get graph order: %w", err)
141 }
142
143 if len(order) != gOrder {
144 return nil, errors.New("topological sort cannot be computed on graph with cycles")
145 }
146
147 return order, nil
148 }
149
150 // TransitiveReduction returns a new graph with the same vertices and the same
151 // reachability as the given graph, but with as few edges as possible. The graph
152 // must be a directed acyclic graph.
153 //
154 // TransitiveReduction is a very expensive operation scaling with O(V(V+E)).
155 func TransitiveReduction[K comparable, T any](g Graph[K, T]) (Graph[K, T], error) {
156 if !g.Traits().IsDirected {
157 return nil, fmt.Errorf("transitive reduction cannot be performed on undirected graph")
158 }
159
160 transitiveReduction, err := g.Clone()
161 if err != nil {
162 return nil, fmt.Errorf("failed to clone the graph: %w", err)
163 }
164
165 adjacencyMap, err := transitiveReduction.AdjacencyMap()
166 if err != nil {
167 return nil, fmt.Errorf("failed to get adajcency map: %w", err)
168 }
169
170 // For each vertex in the graph, run a depth-first search from each direct
171 // successor of that vertex. Then, for each vertex visited within the DFS,
172 // inspect all of its edges. Remove the edges that also appear in the edge
173 // set of the top-level vertex and target the current vertex. These edges
174 // are redundant because their targets apparently are not only reachable
175 // from the top-level vertex, but also through a DFS.
176 for vertex, successors := range adjacencyMap {
177 tOrder, err := transitiveReduction.Order()
178 if err != nil {
179 return nil, fmt.Errorf("failed to get graph order: %w", err)
180 }
181 for successor := range successors {
182 stack := make([]K, 0, tOrder)
183 visited := make(map[K]struct{}, tOrder)
184 onStack := make(map[K]bool, tOrder)
185
186 stack = append(stack, successor)
187
188 for len(stack) > 0 {
189 current := stack[len(stack)-1]
190 stack = stack[:len(stack)-1]
191
192 if _, ok := visited[current]; ok {
193 onStack[current] = false
194 continue
195 }
196
197 visited[current] = struct{}{}
198 onStack[current] = true
199 stack = append(stack, current)
200
201 if len(adjacencyMap[current]) == 0 {
202 onStack[current] = false
203 }
204
205 for adjacency := range adjacencyMap[current] {
206 if _, ok := visited[adjacency]; ok {
207 if onStack[adjacency] {
208 // If the current adjacency is both on the stack and
209 // has already been visited, there is a cycle.
210 return nil, fmt.Errorf("transitive reduction cannot be performed on graph with cycle")
211 }
212 continue
213 }
214
215 if _, ok := adjacencyMap[vertex][adjacency]; ok {
216 _ = transitiveReduction.RemoveEdge(vertex, adjacency)
217 }
218 stack = append(stack, adjacency)
219 }
220 }
221 }
222 }
223
224 return transitiveReduction, nil
225 }