简体   繁体   中英

Using Gonum for graph algorithms in Go

I am a new Go programmer, just finished the "A tour of Go" tutorial a couple days ago. I want to create a graph of a 150 x 120 size and then get all the edge nodes for each node and implement some graph search algorithms such as BFS and Dijkstra. I found a great looking library called Gonum with a graph package that looks promising to use.

My problem is that it is a lot of information and I don't know where to get started. I was hoping there would be a tutorial of some sorts to get me started in the right direction, but I haven't had any luck finding one.

The way I set this up in Python was making a numpy arrays of zero's to represent the size of the graph and then iterate through it to get each edge for each node, but I am not sure that this is the best way to think about how graphs are set up in Go.

If you're just starting with Go I would recommend sticking with the standard library for a bit and not adding more to your learning curve. Try to implement a simple graph data structure with some basic algorithms - it's very easy, and will let you practice with the language. Later on when you need more performance/features, you can look around for libraries (gonum or others). For example, a simple graph can be represented with:

// Node is a node in the graph; it has a (unique) ID and a sequence of
// edges to other nodes.
type Node struct {
    Id    int64
    Edges []int64
}

// Graph contains a set of Nodes, uniquely identified by numeric IDs.
type Graph struct {
    Nodes map[int64]Node
}

Stumbled on this question looking for hints to counting edges with gonum/graph as well. I haven't found a ton of resources other than digging through the API docs.

Think I found the right way to count edges for single nodes.. Maybe!

for _, node := range graph.NodesOf(g.Nodes()) {
    toNodes := g.From(node.ID()) // returns graph.Nodes
    nodeArray := graph.NodesOf( toNodes ) // returns []graph.Node
    edgeCount := len(nodeArray)
    // - or -
    edgeCount := len(graph.NodesOf( g.From(node.ID()) ))
    // do work with edge count
}

Given a known node and all the nodes you can get to from there, you can count (ex: len(graph.NodesOf(g.From(node.ID()))) the number of edges!

To count all of the edges:

totalEdges := len(graph.EdgesOf(g.Edges()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM