首页 > 其他分享 >Go - Creating Graphs

Go - Creating Graphs

时间:2023-10-09 16:16:06浏览次数:40  
标签:node Creating Graph edges Graphs Edges Go Nodes name

Problem: You want to create a weighted graph data structure.


Solution: Create structs for nodes and edges and place them in a Graph struct. Create and attach functions to Graph to create nodes and edges for the graph.

 

Graphs are very common nonlinear data structures that are used everywhere to map relationships between entities. A graph consists of nodes and edges where edges connect two nodes and often represent the relationship between two nodes. Nodes are often given a name and sometimes a value.

You’ll implement a type of graph called the undirected weighted graph , where the edges are also associated with a value, and the edges connect the nodes both ways. As you probably realize, there are many other kinds of graphs, but you can use the same techniques to implement them.

Here are the basic functions of a graph:
AddNode
• Add a new node into the graph
AddEdge
• Add a new edge that connects two nodes
RemoveNode
• Remove an existing node from the graph
RemoveEdge
• Remove an existing edge from the graph

You will use three structs to implement the weighted graph. The Node struct represents a node, with a given name. The Edge struct has a pointer to a node and also a weight. It might look odd but there is a reason for this:

type   Node   struct   { 
      name    string 
} 

type   Edge   struct   { 
      node     * Node 
      weight   int 
} 

type   Graph   struct   { 
      Nodes   [] * Node 
      Edges   map [ string ][] * Edge   //  key  is  node  name 
}

The last is the Graph struct, which represents the weighted graph. The Graph struct has a slice of pointers to Node structs. It also has a map that has a string key that associates with a slice of pointers to Edge structs. The key for this map is the name of the node and the value is a slice of Edge structs.

Edges are implemented using a map so you can’t create a new Graph struct without also initializing the Edges field. To do this you have a function to create a new Graph struct:

func   NewGraph ()   * Graph   { 
      return   & Graph { 
          Edges :   make ( map [ string ][] * Edge ), 
      } 
}

 

func   ( g   * Graph )   AddNode ( n   * Node )   { 
      g . Nodes   =   append ( g . Nodes ,   n ) 
}

func   ( g   * Graph )   AddEdge ( n1 ,   n2   * Node ,   weight   int )   { 
      g . Edges [ n1 . name ]   =   append ( g . Edges [ n1 . name ],   & Edge { n2 ,   weight }) 
      g . Edges [ n2 . name ]   =   append ( g . Edges [ n2 . name ],   & Edge { n1 ,   weight }) 
}

func   ( g   * Graph )   RemoveEdge ( n1 ,   n2   string )   { 
      removeEdge ( g ,   n1 ,   n2 ) 
      removeEdge ( g ,   n2 ,   n1 ) 
} 

func   removeEdge ( g   * Graph ,   m ,   n   string )   { 
      edges   :=   g . Edges [ m ] 
      r   :=   - 1 
      for   i ,   edge   :=   range   edges   { 
          if   edge . node . name   ==   n   { 
              r   =   i 
          } 
      } 
      if   r   >   - 1   { 
          edges [ r ]   =   edges [ len ( edges ) - 1 ] 
          g . Edges [ m ]   =   edges [: len ( edges ) - 1 ] 
      } 
}

func   ( g   * Graph )   RemoveNode ( name   string )   { 
      r   :=   - 1 
      for   i ,   n   :=   range   g . Nodes   { 
          if   n . name   ==   name   { 
              r   =   i 
          } 
      } 
      if   r   >   - 1   { 
          g . Nodes [ r ]   =   g . Nodes [ len ( g . Nodes ) - 1 ]   //  remove  the  node 
          g . Nodes   =   g . Nodes [: len ( g . Nodes ) - 1 ] 
      } 
      delete ( g . Edges ,   name )   //  remove  the  edge  from  one  side 
      //  remove  the  edge  from  the  other  side 
      for   n   :=   range   g . Edges   { 
          removeEdge ( g ,   n ,   name ) 
      } 
}

Removing an edge is a bit more involved. The edges are in a slice that are the values in the Edges map, so you need to iterate through them and mark it if it’s to be removed. Once you find out where the edge is, take the last element in the slice and place it at the index, effectively removing that edge. After that, reslice to truncate the last element. You have to do this twice to remove edges from both directions since this is an undirected graph.

Removing nodes is also a bit more involved but very much the same as removing edges. First, you need to find out the index of the node to remove. Once you do that you take the last element in the slice and place it at the index, then truncate the last element. You also need to remove the edges that are connected to the node. First, delete the edge from the Edges map. Then go through the rest of the other key - value pairs and remove the node accordingly.

 

标签:node,Creating,Graph,edges,Graphs,Edges,Go,Nodes,name
From: https://www.cnblogs.com/zhangzhihui/p/17751902.html

相关文章

  • RunnerGo亮相QECon大会上海站,来看看这款全栈测试平台
    QECon(QualityEfficiencyConference)质量效能大会在上海正式开幕!本次大会以"数生智慧:高质量发展新引擎"为主题,深入探讨如何借助数字化和智能化技术推动软件质量的发展,为高质量经济发展提供新动力。测试行业的发展历程:在互联网初期,软件测试并未被视为独立的职业领域,而是开发人员在......
  • Golang 使用SQLX实现可选条件查询
    packagemainimport( "fmt" "log" _"github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx")typeCityQuerystruct{ querystring optscityQueryOptions params[]any}typecityQueryOptionsstruct{......
  • Go - Creating Heaps
    Problem: Youwanttocreateaminheapdatastructure.Solution: Wrapastructaroundasliceofelementstorepresentaheap.Aftereachpushorpopontheheap,rearrangetheheapstructure. AHeapisaspecialTree-baseddatastructureinwhichthe......
  • MongoDB下载安装入门
    MongoDB下载安装入门一.MongoDB下载安装mongodb官网下载不了,MongoDB下载、安装、配置、使用,如何下载MongoDB数据库,MongoDB入门-CSDN博客按照文章一→六:安装,下载,环境变量配置等等MongoDBv4.2版安装目录:C:\ProgramFiles\MongoDB\Server\4.2\bin二.安全认证注意!!!一定要......
  • allure 报告页面logo和名称定制
    1)找到本地allure安装路径,找到static文件夹(我的是:/Users/may/Downloads/allure-2.7.0/plugins/custom-logo-plugin/static), 将要更换的图片放入这个文件夹中,命名为allure_log.jpeg 2)修改取值文件,在同一个文件夹(static)下,找到styles.css,打开该文件(不建议用记事本)原来代码如......
  • mongodb慢查询对内存和CPU的影响
    所得结果均为ChatGPT所得,只是用来记录好复习对内存的影响数据加载到内存:MongoDB使用内存来缓存最频繁访问的数据,以提高查询性能。这个缓存通常称为"工作集"。当一个查询需要访问某些数据时,MongoDB会尝试从内存中获取数据,这比从磁盘读取数据要快得多。慢查询导致数据逐出:当......
  • Gogs私服搭建
    1.Gogs介绍官网地址:https://gogs.io 文档地址:https://gogs.io/docs Gogs,全称为GoGitService,是一个基于Go语言开发的Git服务。它提供了一个类似于GitHub的界面和功能,允许您在自己的服务器上搭建私有的Git仓库和代码托管平台(类似gitlab)。Gogs是一个轻量级的Git......
  • Go - Creating Linked Lists
    Problem: Youwanttocreatealinkedlistdatastructure.Solution: Createanelementstructthathasapointertothenextelement.Wrapanotherstructaroundthefirstelementtocreatealinkedlist. Alinkedlistisalinearcollectionofelements......
  • 【最佳实践】MongoDB导出导入数据
    首先说一下这个3节点MongoDB集群各个维度的数据规模:1、dataSize:1.9T2、storageSize:600G3、全量备份-加压缩开关:186G,耗时8h4、全量备份-不加压缩开关:1.8T,耗时4h27m具体导出的语法比较简单,此处不再赘述,本文重点描述导入的优化过程,最后给出导入的最佳实践。■2023-09-13......
  • Go 复合类型之切片类型介绍
    Go复合类型之切片类型目录Go复合类型之切片类型一、引入二、切片(Slice)概述2.1基本介绍2.2特点2.3切片与数组的区别三、切片声明与初始化3.1方式一:使用切片字面量初始化3.2方式二:使用make函数初始化3.3方式三:基于数组的切片化四、切片的本质(底层实现原理)五、切片的动......