我试图通过一些简单的图表更好地理解 golang。我在课堂上尝试过这个,但我无法真正弄清楚。问题是我知道解决方案非常简单。我试图让它通过读取边缘来打印每条单独的路径。我已经玩过相当多的代码了,这确实是我能得到的最简单的形式。package mainimport "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 -> CEdge: A -> BEdge: A -> DEdge: D -> Emap[A:[B D] B:[C] D:[E]]A -> BB -> CA -> DD -> E% 我希望看到 Walk 方法做这样的事情:A -> B -> CA -> D -> E
1 回答
潇湘沐
TA贡献1816条经验 获得超6个赞
实际上,代码中有很多内容可以更改。Walk
但是,对检查是否为基边的函数的快速修复可以修复格式问题。main
现在应该从with调用它g.Walk("A", true)
。
func (g *Graph) Walk(u string, f bool) {
for _, v := range g.Edges[u] {
if f == true {
fmt.Printf("\n%s -> %s", u, v)
} else {
fmt.Printf(" -> %s", v)
}
g.Walk(v, false)
}
}
编辑 实际上,您可以只检查f然后将您设置为"\n + u"相应的:
func (g *Graph) Walk(u string, f bool) {
for _, v := range g.Edges[u] {
if f {
u = "\n" + u
} else {
u = ""
}
fmt.Printf("%s -> %s", u, v)
g.Walk(v, false)
}
}
- 1 回答
- 0 关注
- 97 浏览
添加回答
举报
0/150
提交
取消