我试图通过一些简单的图表更好地理解 golang。我在课堂上尝试过这个,但我无法真正弄清楚。问题是我知道解决方案非常简单。我试图让它通过读取边缘来打印每条单独的路径。
我已经玩过相当多的代码了,这确实是我能得到的最简单的形式。
package main
import "fmt"
type Graph struct {
Edges map[string][]string
}
// NewGraph: Create graph with n nodes.
func NewGraph() *Graph {
return &Graph{
Edges: make(map[string][]string),
}
}
// AddEdge: Add an edge from u to v.
func (g *Graph) AddEdge(u, v string) {
g.Edges[u] = append(g.Edges[u], v)
}
func (g *Graph) Walk(u string) {
for _, v := range g.Edges[u] {
fmt.Printf("%s -> %s", u, v)
g.Walk(v)
}
}
func (g *Graph) adjacentEdgesExample() {
fmt.Println("Printing all edges in graph.")
for u, adjacent := range g.Edges { // Nodes are labelled 0 to N-1.
for _, v := range adjacent {
// Edge exists from u to v.
fmt.Printf("Edge: %s -> %s\n", u, v)
}
}
}
func main() {
g := NewGraph()
g.AddEdge("A", "B")
g.AddEdge("A", "D")
g.AddEdge("D", "E")
g.AddEdge("B", "C")
g.adjacentEdgesExample()
fmt.Println(g.Edges)
g.Walk("A")
}
示例位于:
https://goplay.space/#Ro1puZYgu5X
其结果是:
Printing all edges in graph.
Edge: B -> C
Edge: A -> B
Edge: A -> D
Edge: D -> E
map[A:[B D] B:[C] D:[E]]
A -> BB -> CA -> DD -> E%
我希望看到 Walk 方法做这样的事情:
A -> B -> C
A -> D -> E
潇湘沐
相关分类