AddEdge adds an edge to the graph. It initializes the graph and metadata on first use, checks for cycles, and adds the edge to the gonum graph.
(from, to VertexType, edge EdgeType)
| 43 | // AddEdge adds an edge to the graph. It initializes the graph and metadata on first use, |
| 44 | // checks for cycles, and adds the edge to the gonum graph. |
| 45 | func (g *Graph[EdgeType, VertexType]) AddEdge(from, to VertexType, edge EdgeType) error { |
| 46 | g.mu.Lock() |
| 47 | defer g.mu.Unlock() |
| 48 | |
| 49 | if g.gonumGraph == nil { |
| 50 | g.gonumGraph = simple.NewDirectedGraph() |
| 51 | g.vertexToID = make(map[VertexType]int64) |
| 52 | g.idToVertex = make(map[int64]VertexType) |
| 53 | g.edgeTypes = make(map[string]EdgeType) |
| 54 | g.nextID = 1 |
| 55 | } |
| 56 | |
| 57 | fromID := g.getOrCreateVertexID(from) |
| 58 | toID := g.getOrCreateVertexID(to) |
| 59 | |
| 60 | if g.canReach(to, from) { |
| 61 | return xerrors.Errorf("adding edge (%v -> %v): %w", from, to, ErrCycleDetected) |
| 62 | } |
| 63 | |
| 64 | g.gonumGraph.SetEdge(simple.Edge{F: simple.Node(fromID), T: simple.Node(toID)}) |
| 65 | |
| 66 | edgeKey := fmt.Sprintf("%d->%d", fromID, toID) |
| 67 | g.edgeTypes[edgeKey] = edge |
| 68 | |
| 69 | return nil |
| 70 | } |
| 71 | |
| 72 | // GetForwardAdjacentVertices returns all the edges that originate from the given vertex. |
| 73 | func (g *Graph[EdgeType, VertexType]) GetForwardAdjacentVertices(from VertexType) []Edge[EdgeType, VertexType] { |