package pov
type myArc struct {
from string
to string
}
type Graph struct {
nodes []string
arcs []myArc
}
func New() *Graph {
return &Graph{}
}
func (g *Graph) AddNode(nodeLabel string) {
g.nodes = append(g.nodes, nodeLabel)
}
func (g *Graph) AddArc(from, to string) {
g.arcs = append(g.arcs, myArc{from, to})
}
func (g *Graph) ArcList() []string {
var ret []string
for _, a := range g.arcs {
ret = append(ret, a.from+" -> "+a.to)
}
return ret
}
func (g *Graph) ChangeRoot(oldRoot, newRoot string) *Graph {
// copy the original graph nodes
ret := &Graph{}
for _, node := range g.nodes {
ret.nodes = append(ret.nodes, node)
}
// reparenting
route := make(chan string, 1)
for _, a := range g.arcs {
if a.to == newRoot {
route <- a.from
a.from, a.to = a.to, a.from
}
ret.arcs = append(ret.arcs, a)
}
for {
select {
case elem := <-route:
if elem == oldRoot {
break
}
for i, a := range g.arcs {
if a.to == elem {
route <- a.from
a.to, a.from = a.from, a.to
ret.arcs[i] = a
}
}
default:
return ret
}
}
}