Ai
4 Star 12 Fork 8

ShirDon-廖显东/零基础Go语言算法实战源码

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
directedGraph.go 1.51 KB
一键复制 编辑 原始数据 按行查看 历史
ShirDon-廖显东 提交于 2024-04-22 14:56 +08:00 . first commit
// ++++++++++++++++++++++++++++++++++++++++
// 《零基础Go语言算法实战》源码
// ++++++++++++++++++++++++++++++++++++++++
// Author:廖显东(ShirDon)
// Blog:https://www.shirdon.com/
// Gitee:https://gitee.com/shirdonl/goAlgorithms.git
// Buy link :https://item.jd.com/14101229.html
// ++++++++++++++++++++++++++++++++++++++++
package main
import "fmt"
// 有向图
type directedGraph struct {
nodes []*GraphNode
}
// 有向图节点
type GraphNode struct {
id int
edges map[int]int
}
// 初始化图对象
func New() *directedGraph {
return &directedGraph{
nodes: []*GraphNode{},
}
}
// 向图Graph中添加一个新节点
func (dg *directedGraph) AddNode() (id int) {
id = len(dg.nodes)
dg.nodes = append(dg.nodes, &GraphNode{
id: id,
edges: make(map[int]int),
})
return
}
// 将方向边与权重一起添加
func (dg *directedGraph) AddEdge(node1, node2 int, w int) {
dg.nodes[node1].edges[node2] = w
}
// 返回节点 ID 列表
func (dg *directedGraph) Nodes() []int {
nodes := make([]int, len(dg.nodes))
for i := range dg.nodes {
nodes[i] = i
}
return nodes
}
// 添加边
func (dg *directedGraph) Edges() [][3]int {
edges := make([][3]int, 0, len(dg.nodes))
for i := 0; i < len(dg.nodes); i++ {
for k, v := range dg.nodes[i].edges {
edges = append(edges, [3]int{i, k, int(v)})
}
}
return edges
}
func main() {
directedGraph := New()
directedGraph.AddNode()
directedGraph.AddNode()
res := directedGraph.Nodes()
fmt.Println(res)
}
//$ go run directedGraph.go
//[0 1]
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/shirdonl/goAlgorithms.git
git@gitee.com:shirdonl/goAlgorithms.git
shirdonl
goAlgorithms
零基础Go语言算法实战源码
3e77a12194dd

搜索帮助