Skip to content

Instantly share code, notes, and snippets.

@alpinskiy
Created September 11, 2015 15:56
Show Gist options
  • Save alpinskiy/3a8ab6b184c444bc819d to your computer and use it in GitHub Desktop.
Save alpinskiy/3a8ab6b184c444bc819d to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"fmt"
)
type Node string
type Graph struct {
al map[Node]map[Node]bool // adjacency list
}
func NewGraph() Graph {
return Graph{al: make(map[Node]map[Node]bool)}
}
func (g *Graph) AddNode(n Node) {
al := g.al
_, ok := al[n]
if !ok {
al[n] = make(map[Node]bool)
}
}
func (g *Graph) AddEdge(tail Node, head Node) {
g.AddNode(tail)
g.AddNode(head)
g.al[tail][head] = true
}
func (g *Graph) String() string {
var buffer bytes.Buffer
buffer.WriteString("digraph {\n")
ids := make(map[Node]int)
id := 0
for node := range g.al {
id++
ids[node] = id
buffer.WriteString(fmt.Sprintf(" %v [label=%v]\n", id, node))
}
for tail, heads := range g.al {
for head := range heads {
buffer.WriteString(fmt.Sprintf(" %v -> %v\n", ids[tail], ids[head]))
}
}
buffer.WriteString("}\n")
return buffer.String()
}
func main() {
g := NewGraph()
g.AddEdge("one", "two")
g.AddEdge("two", "three")
g.AddEdge("three", "one")
fmt.Println(g)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment