golang 有向无环图代码
时间: 2023-12-12 18:33:25 浏览: 132
自己动手用Golang实现约瑟夫环算法的示例
以下是一个使用Golang实现有向无环图的代码示例:
```go
package main
import (
"fmt"
)
type Graph struct {
nodes []int
edges map[int][]int
}
func (g *Graph) addNode(node int) {
g.nodes = append(g.nodes, node)
}
func (g *Graph) addEdge(from, to int) {
if g.edges == nil {
g.edges = make(map[int][]int)
}
g.edges[from] = append(g.edges[from], to)
}
func (g *Graph) topologicalSort() []int {
inDegree := make(map[int]int)
for _, node := range g.nodes {
inDegree[node] = 0
}
for _, edges := range g.edges {
for _, to := range edges {
inDegree[to]++
}
}
queue := []int{}
for node, degree := range inDegree {
if degree == 0 {
queue = append(queue, node)
}
}
result := []int{}
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
result = append(result, node)
for _, to := range g.edges[node] {
inDegree[to]--
if inDegree[to] == 0 {
queue = append(queue, to)
}
}
}
return result
}
func main() {
g := Graph{}
g.addNode(1)
g.addNode(2)
g.addNode(3)
g.addNode(4)
g.addEdge(1, 2)
g.addEdge(1, 3)
g.addEdge(2, 4)
g.addEdge(3, 4)
sorted := g.topologicalSort()
fmt.Println(sorted)
}
```
阅读全文