-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.go
More file actions
48 lines (41 loc) · 891 Bytes
/
graph.go
File metadata and controls
48 lines (41 loc) · 891 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package bubble
import "slices"
type graph[T comparable] struct {
vertices []T
edges map[T][]T
vis map[T]struct{}
stack []T
}
func newGraph[T comparable]() *graph[T] {
return &graph[T]{
edges: make(map[T][]T),
vis: make(map[T]struct{}),
}
}
func (g *graph[T]) addVertex(u T) {
g.vertices = append(g.vertices, u)
}
func (g *graph[T]) addEdge(u T, v T) {
g.edges[u] = append(g.edges[u], v)
}
func (g *graph[T]) traverse(u T) {
g.vis[u] = struct{}{}
for _, v := range g.edges[u] {
if _, ok := g.vis[v]; !ok {
g.traverse(v)
}
}
g.stack = append(g.stack, u)
}
func (g *graph[T]) sort(cmp func(T, T) int) []T {
slices.SortStableFunc(g.vertices, cmp)
for k := range g.edges {
g.edges[k] = slices.SortedStableFunc(slices.Values(g.edges[k]), cmp)
}
for _, v := range g.vertices {
if _, ok := g.vis[v]; !ok {
g.traverse(v)
}
}
return g.stack
}