dominikbraun / graph

A library for creating generic graph data structures and modifying, analyzing, and visualizing them.
https://graph.dominikbraun.io
Apache License 2.0
1.77k stars 95 forks source link

Query edges from/to given vertex #151

Closed wylswz closed 11 months ago

wylswz commented 11 months ago

Is it possible to add methods like this to Graph[K, T]

EdgesFrom(sourceHash K) ([]Edge[K], error)
EdgesTo(targetHash K) ([]Edge[K], error)

Currently I need to fetch all edges, and filter them by Target and Source property, which doesn't seem to scale

dominikbraun commented 11 months ago

Would using the adjacency and predecessor maps work for you?

adjacencyMap, _ := g.AdjacencyMap()

for target, edge := adjacencyMap[myVertex] {
    // This is an outgoing edge of myVertex.
    fmt.Println(edge)
}

predecessorMap, _ := g. PredecessorMap()

for source, edge := predecessorMap[myVertex] {
    // This is an ingoing edge of myVertex.
    fmt.Println(edge)
}
wylswz commented 11 months ago

That computes maps from scratch every time, still get O(V+E) time complexity

    for _, vertex := range vertices {
        m[vertex] = make(map[K]Edge[K])
    }

    for _, edge := range edges {
        m[edge.Source][edge.Target] = edge
    }

I can add some caches for now (given that my graph isn't updated very frequently)

wylswz commented 11 months ago

Tested out cached adjMap & predMap solution, that worked fine for me. Thanks for your reply, will close this issue

dominikbraun commented 11 months ago

@wylswz Your suggestion of adding functions like EdgesFrom is good though, I'm going to dig into it.