Debian Codegraph @

paths.go

raw symbols SCIP
1 package graph
2
3 import (
4 "errors"
5 "fmt"
6 "math"
7 )
8
9 var ErrTargetNotReachable = errors.New("target vertex not reachable from source")
10
11 // CreatesCycle determines whether adding an edge between the two given vertices
12 // would introduce a cycle in the graph. CreatesCycle will not create an edge.
13 //
14 // A potential edge would create a cycle if the target vertex is also a parent
15 // of the source vertex. In order to determine this, CreatesCycle runs a DFS.
16 func CreatesCycle[K comparable, T any](g Graph[K, T], source, target K) (bool, error) {
17 if _, err := g.Vertex(source); err != nil {
18 return false, fmt.Errorf("could not get vertex with hash %v: %w", source, err)
19 }
20
21 if _, err := g.Vertex(target); err != nil {
22 return false, fmt.Errorf("could not get vertex with hash %v: %w", target, err)
23 }
24
25 if source == target {
26 return true, nil
27 }
28
29 predecessorMap, err := g.PredecessorMap()
30 if err != nil {
31 return false, fmt.Errorf("failed to get predecessor map: %w", err)
32 }
33
34 stack := make([]K, 0)
35 visited := make(map[K]bool)
36
37 stack = append(stack, source)
38
39 for len(stack) > 0 {
40 currentHash := stack[len(stack)-1]
41 stack = stack[:len(stack)-1]
42
43 if _, ok := visited[currentHash]; !ok {
44 // If the adjacent vertex also is the target vertex, the target is a
45 // parent of the source vertex. An edge would introduce a cycle.
46 if currentHash == target {
47 return true, nil
48 }
49
50 visited[currentHash] = true
51
52 for adjacency := range predecessorMap[currentHash] {
53 stack = append(stack, adjacency)
54 }
55 }
56 }
57
58 return false, nil
59 }
60
61 // ShortestPath computes the shortest path between a source and a target vertex
62 // under consideration of the edge weights. It returns a slice of hash values of
63 // the vertices forming that path.
64 //
65 // The returned path includes the source and target vertices. If the target is
66 // not reachable from the source, ErrTargetNotReachable will be returned. Should
67 // there be multiple shortest paths, and arbitrary one will be returned.
68 //
69 // ShortestPath has a time complexity of O(|V|+|E|log(|V|)).
70 func ShortestPath[K comparable, T any](g Graph[K, T], source, target K) ([]K, error) {
71 weights := make(map[K]float64)
72 visited := make(map[K]bool)
73
74 weights[source] = 0
75 visited[target] = true
76
77 queue := newPriorityQueue[K]()
78 adjacencyMap, err := g.AdjacencyMap()
79 if err != nil {
80 return nil, fmt.Errorf("could not get adjacency map: %w", err)
81 }
82
83 for hash := range adjacencyMap {
84 if hash != source {
85 weights[hash] = math.Inf(1)
86 visited[hash] = false
87 }
88
89 queue.Push(hash, weights[hash])
90 }
91
92 // bestPredecessors stores the cheapest or least-weighted predecessor for
93 // each vertex. Given an edge AC with weight=4 and an edge BC with weight=2,
94 // the cheapest predecessor for C is B.
95 bestPredecessors := make(map[K]K)
96
97 for queue.Len() > 0 {
98 vertex, _ := queue.Pop()
99 hasInfiniteWeight := math.IsInf(weights[vertex], 1)
100
101 for adjacency, edge := range adjacencyMap[vertex] {
102 edgeWeight := edge.Properties.Weight
103
104 // Setting the weight to 1 is required for unweighted graphs whose
105 // edge weights are 0. Otherwise, all paths would have a sum of 0
106 // and a random path would be returned.
107 if !g.Traits().IsWeighted {
108 edgeWeight = 1
109 }
110
111 weight := weights[vertex] + float64(edgeWeight)
112
113 if weight < weights[adjacency] && !hasInfiniteWeight {
114 weights[adjacency] = weight
115 bestPredecessors[adjacency] = vertex
116 queue.UpdatePriority(adjacency, weight)
117 }
118 }
119 }
120
121 path := []K{target}
122 current := target
123
124 for current != source {
125 // If the current vertex is not present in bestPredecessors, current is
126 // set to the zero value of K. Without this check, this would lead to an
127 // endless prepending of zero values to the path. Also, the target would
128 // not be reachable from one of the preceding vertices.
129 if _, ok := bestPredecessors[current]; !ok {
130 return nil, ErrTargetNotReachable
131 }
132 current = bestPredecessors[current]
133 path = append([]K{current}, path...)
134 }
135
136 return path, nil
137 }
138
139 type sccState[K comparable] struct {
140 adjacencyMap map[K]map[K]Edge[K]
141 components [][]K
142 stack []K
143 onStack map[K]bool
144 visited map[K]struct{}
145 lowlink map[K]int
146 index map[K]int
147 time int
148 }
149
150 // StronglyConnectedComponents detects all strongly connected components within
151 // the graph and returns the hashes of the vertices shaping these components, so
152 // each component is represented by a []K.
153 //
154 // StronglyConnectedComponents can only run on directed graphs.
155 func StronglyConnectedComponents[K comparable, T any](g Graph[K, T]) ([][]K, error) {
156 if !g.Traits().IsDirected {
157 return nil, errors.New("SCCs can only be detected in directed graphs")
158 }
159
160 adjacencyMap, err := g.AdjacencyMap()
161 if err != nil {
162 return nil, fmt.Errorf("could not get adjacency map: %w", err)
163 }
164
165 state := &sccState[K]{
166 adjacencyMap: adjacencyMap,
167 components: make([][]K, 0),
168 stack: make([]K, 0),
169 onStack: make(map[K]bool),
170 visited: make(map[K]struct{}),
171 lowlink: make(map[K]int),
172 index: make(map[K]int),
173 }
174
175 for hash := range state.adjacencyMap {
176 if _, ok := state.visited[hash]; !ok {
177 findSCC(hash, state)
178 }
179 }
180
181 return state.components, nil
182 }
183
184 func findSCC[K comparable](vertexHash K, state *sccState[K]) {
185 state.stack = append(state.stack, vertexHash)
186 state.onStack[vertexHash] = true
187 state.visited[vertexHash] = struct{}{}
188 state.index[vertexHash] = state.time
189 state.lowlink[vertexHash] = state.time
190
191 state.time++
192
193 for adjacency := range state.adjacencyMap[vertexHash] {
194 if _, ok := state.visited[adjacency]; !ok {
195 findSCC(adjacency, state)
196
197 smallestLowlink := math.Min(
198 float64(state.lowlink[vertexHash]),
199 float64(state.lowlink[adjacency]),
200 )
201 state.lowlink[vertexHash] = int(smallestLowlink)
202 } else {
203 // If the adjacent vertex already is on the stack, the edge joining
204 // the current and the adjacent vertex is a back ege. Therefore, the
205 // lowlink value of the vertex has to be updated to the index of the
206 // adjacent vertex if it is smaller than the current lowlink value.
207 if state.onStack[adjacency] {
208 smallestLowlink := math.Min(
209 float64(state.lowlink[vertexHash]),
210 float64(state.index[adjacency]),
211 )
212 state.lowlink[vertexHash] = int(smallestLowlink)
213 }
214 }
215 }
216
217 // If the lowlink value of the vertex is equal to its DFS value, this is the
218 // head vertex of a strongly connected component that's shaped by the vertex
219 // and all vertices on the stack.
220 if state.lowlink[vertexHash] == state.index[vertexHash] {
221 var hash K
222 var component []K
223
224 for hash != vertexHash {
225 hash = state.stack[len(state.stack)-1]
226 state.stack = state.stack[:len(state.stack)-1]
227 state.onStack[hash] = false
228
229 component = append(component, hash)
230 }
231
232 state.components = append(state.components, component)
233 }
234 }
235
236 // AllPathsBetween computes and returns all paths between two given vertices. A
237 // path is represented as a slice of vertex hashes. The returned slice contains
238 // these paths.
239 //
240 // AllPathsBetween utilizes a non-recursive, stack-based implementation. It has
241 // an estimated runtime complexity of O(n^2) where n is the number of vertices.
242 func AllPathsBetween[K comparable, T any](g Graph[K, T], start, end K) ([][]K, error) {
243 adjacencyMap, err := g.AdjacencyMap()
244 if err != nil {
245 return nil, err
246 }
247
248 // The algorithm used relies on stacks instead of recursion. It is described
249 // here: https://boycgit.github.io/all-paths-between-two-vertex/
250 mainStack := newStack[K]()
251 viceStack := newStack[stack[K]]()
252
253 checkEmpty := func() error {
254 if mainStack.isEmpty() || viceStack.isEmpty() {
255 return errors.New("empty stack")
256 }
257 return nil
258 }
259
260 buildLayer := func(element K) {
261 mainStack.push(element)
262
263 newElements := newStack[K]()
264 for e := range adjacencyMap[element] {
265 var contains bool
266 mainStack.forEach(func(k K) {
267 if e == k {
268 contains = true
269 }
270 })
271 if contains {
272 continue
273 }
274 newElements.push(e)
275 }
276 viceStack.push(newElements)
277 }
278
279 buildStack := func() error {
280 if err = checkEmpty(); err != nil {
281 return fmt.Errorf("unable to build stack: %w", err)
282 }
283
284 elements, _ := viceStack.top()
285
286 for !elements.isEmpty() {
287 element, _ := elements.pop()
288 buildLayer(element)
289 elements, _ = viceStack.top()
290 }
291
292 return nil
293 }
294
295 removeLayer := func() error {
296 if err = checkEmpty(); err != nil {
297 return fmt.Errorf("unable to remove layer: %w", err)
298 }
299
300 if e, _ := viceStack.top(); !e.isEmpty() {
301 return errors.New("the top element of vice-stack is not empty")
302 }
303
304 _, _ = mainStack.pop()
305 _, _ = viceStack.pop()
306
307 return nil
308 }
309
310 buildLayer(start)
311
312 allPaths := make([][]K, 0)
313
314 for !mainStack.isEmpty() {
315 v, _ := mainStack.top()
316 adjs, _ := viceStack.top()
317
318 if adjs.isEmpty() {
319 if v == end {
320 path := make([]K, 0)
321 mainStack.forEach(func(k K) {
322 path = append(path, k)
323 })
324 allPaths = append(allPaths, path)
325 }
326
327 err = removeLayer()
328 if err != nil {
329 return nil, err
330 }
331 } else {
332 if err = buildStack(); err != nil {
333 return nil, err
334 }
335 }
336 }
337
338 return allPaths, nil
339 }