| 1 |
// Copyright 2026 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package graph |
| 6 |
|
| 7 |
import ( |
| 8 |
"iter" |
| 9 |
"maps" |
| 10 |
"slices" |
| 11 |
) |
| 12 |
|
| 13 |
// testGraph is a simple adjacency list implementation of [CompactGraph] for testing. |
| 14 |
type testGraph struct { |
| 15 |
nodes int |
| 16 |
edges map[int][]int |
| 17 |
} |
| 18 |
|
| 19 |
// newTestGraph builds a testGraph from an adjacency list represented as a map. |
| 20 |
func newTestGraph(n int, adj map[int][]int) *testGraph { |
| 21 |
return &testGraph{ |
| 22 |
nodes: int(n), |
| 23 |
edges: adj, |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
func (g *testGraph) Nodes() iter.Seq[int] { |
| 28 |
return func(yield func(int) bool) { |
| 29 |
for i := range g.nodes { |
| 30 |
if !yield(i) { |
| 31 |
break |
| 32 |
} |
| 33 |
} |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
func (g *testGraph) NumNodes() int { |
| 38 |
return g.nodes |
| 39 |
} |
| 40 |
|
| 41 |
func (g *testGraph) Out(u int) iter.Seq[int] { |
| 42 |
return slices.Values(g.edges[u]) |
| 43 |
} |
| 44 |
|
| 45 |
func (g *testGraph) IsCompact() {} |
| 46 |
|
| 47 |
// stringGraph implements Graph[string]. |
| 48 |
type stringGraph map[string][]string |
| 49 |
|
| 50 |
func (g stringGraph) Nodes() iter.Seq[string] { |
| 51 |
return maps.Keys(g) |
| 52 |
} |
| 53 |
|
| 54 |
func (g stringGraph) NumNodes() int { |
| 55 |
return len(g) |
| 56 |
} |
| 57 |
|
| 58 |
func (g stringGraph) Out(node string) iter.Seq[string] { |
| 59 |
return func(yield func(string) bool) { |
| 60 |
for _, succ := range g[node] { |
| 61 |
if !yield(succ) { |
| 62 |
return |
| 63 |
} |
| 64 |
} |
| 65 |
} |
| 66 |
} |