Debian Codegraph @

path.go

raw symbols SCIP
1 package graph
2
3 // ShortestPath computes a shortest path from v to w.
4 // Only edges with non-negative costs are included.
5 // The number dist is the length of the path, or -1 if w cannot be reached.
6 //
7 // The time complexity is O((|E| + |V|)⋅log|V|), where |E| is the number of edges
8 // and |V| the number of vertices in the graph.
9 func ShortestPath(g Iterator, v, w int) (path []int, dist int64) {
10 parent, distances := ShortestPaths(g, v)
11 path, dist = []int{}, distances[w]
12 if dist == -1 {
13 return
14 }
15 for v := w; v != -1; v = parent[v] {
16 path = append(path, v)
17 }
18 for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {
19 path[i], path[j] = path[j], path[i]
20 }
21 return
22 }
23
24 // ShortestPaths computes the shortest paths from v to all other vertices.
25 // Only edges with non-negative costs are included.
26 // The number parent[w] is the predecessor of w on a shortest path from v to w,
27 // or -1 if none exists.
28 // The number dist[w] equals the length of a shortest path from v to w,
29 // or is -1 if w cannot be reached.
30 //
31 // The time complexity is O((|E| + |V|)⋅log|V|), where |E| is the number of edges
32 // and |V| the number of vertices in the graph.
33 func ShortestPaths(g Iterator, v int) (parent []int, dist []int64) {
34 n := g.Order()
35 dist = make([]int64, n)
36 parent = make([]int, n)
37 for i := range dist {
38 dist[i], parent[i] = -1, -1
39 }
40 dist[v] = 0
41
42 // Dijkstra's algorithm
43 Q := emptyPrioQueue(dist)
44 Q.Push(v)
45 for Q.Len() > 0 {
46 v := Q.Pop()
47 g.Visit(v, func(w int, d int64) (skip bool) {
48 if d < 0 {
49 return
50 }
51 alt := dist[v] + d
52 switch {
53 case dist[w] == -1:
54 dist[w], parent[w] = alt, v
55 Q.Push(w)
56 case alt < dist[w]:
57 dist[w], parent[w] = alt, v
58 Q.Fix(w)
59 }
60 return
61 })
62 }
63 return
64 }