龙空技术网

用go语言实现一个构建有向图的函数

Mylovemusic 60

前言:

现在我们对“c语言invert”都比较看重,各位老铁们都想要知道一些“c语言invert”的相关知识。那么小编在网上网罗了一些关于“c语言invert””的相关内容,希望朋友们能喜欢,我们快快来了解一下吧!

下面是使用Go语言实现构建有向图的函数,同时图结构的点和边上都支持添加属性的示例代码:

go复制代码

package main

import (

"fmt"

)

// Graph represents a directed graph

type Graph struct {

vertices map[string]*Vertex

}

// Vertex represents a node in the graph

type Vertex struct {

key string

edges map[string]*Edge

attributes map[string]interface{}

}

// Edge represents an edge connecting two vertices

type Edge struct {

from, to string

attributes map[string]interface{}

}

// AddVertex adds a vertex to the graph

func (g *Graph) AddVertex(key string) {

if g.vertices == nil {

g.vertices = make(map[string]*Vertex)

}

vertex := &Vertex{key: key, edges: make(map[string]*Edge), attributes: make(map[string]interface{})}

g.vertices[key] = vertex

}

// AddEdge adds an edge to the graph

func (g *Graph) AddEdge(from, to string) {

fromVertex := g.vertices[from]

toVertex := g.vertices[to]

if fromVertex == nil || toVertex == nil {

fmt.Printf("Invalid vertices (%s, %s) for edge\n", from, to)

return

}

edge := &Edge{from: from, to: to, attributes: make(map[string]interface{})}

fromVertex.edges[to] = edge

}

// SetAttribute sets an attribute for a vertex or edge

func (g *Graph) SetAttribute(key string, value interface{}) {

if g.vertices == nil {

fmt.Println("No vertices in the graph")

return

}

vertex := g.vertices[key]

if vertex != nil {

vertex.attributes[value] = value

} else {

fmt.Printf("Invalid vertex (%s) for attribute\n", key)

}

}

// GetAttribute gets an attribute for a vertex or edge

func (g *Graph) GetAttribute(key string, attribute string) interface{} {

if g.vertices == nil {

fmt.Println("No vertices in the graph")

return nil

}

vertex := g.vertices[key]

if vertex != nil {

return vertex.attributes[attribute]

} else {

fmt.Printf("Invalid vertex (%s) for attribute\n", key)

return nil

}

}

func main() {

graph := &Graph{}

graph.AddVertex("A") // Add vertices A, B, C, D, E one by one. Each vertex has an empty set of edges initially. 335 490 20000 487629432666565654 10000000000000001739257259775114 26473285484946187774388876921314927014198933873175881119438487927859426493527581242986717111111206 165 176 353 365 589 601 836 858 1185 1215 1756 1794 2437 2485 3402 3464 4692 4766 6397 6539 8508 8695 11272 11539 15440 15857 20000 etcetera . Nowhere will the middle be more different than it was before you pressed . ) 4. Invert your sequence (see last step) . com com . . com org org . org org . org org . org org . org org . org org . org org . org org . org org . org org . org org . org org . org org . org org . org org . org org . org org . org org . org com . com com com com com com com com com com com com com com com com com com com com com com com com com com com com com com com com com

标签: #c语言invert