程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python] create weighted undirected connected graph

編輯:Python
problem : Use Prim Algorithm for minimum spanning tree , You have to have a weighted connected graph , Ask how to use this code to create a weighted connected graph as shown in the following figure

Use the following code to create
import copyfrom typing import ListMAXV = 10 # Maximum number of vertices INF = 0x3f3f3f3f # ( Hexadecimal ) Express ∞# Design adjacency matrix class class MatGraph: def __init__(self, n=0, e=0): self.edges = [] self.vexs = [] self.n = n self.e = edef CreateMatGraph(self,a,n,e): # Create an adjacency matrix  self.n = n # Number of vertices n self.e = e # Number of edges e self.edges = copy.deepcopy(a) # Deep copy to adjacency matrix adef DisMatGraph(self): # Adjacency matrix of output graph  for i in range(self.n): for j in range(self.n): if self.edges[i][j] == INF: print("%4s"%("∞"),end='') else: print("%5d"%(self.edges[i][j]),end='') print()# Prim The algorithm constructs the minimum spanning tree def Prim(g,v): global min, k lowcost = [0]*MAXV # Build array : Minimum weight  closest = [0]*MAXV # Build array : Some recent  for i in range(g.n): # to lowcost[] and closest[] Set the initial value ,i Is the number of a vertex  lowcost[i] = g.edges[v][i] # lowcost[] Record the weight of the edge  closest[i] = v # closest[] Record the nearest vertex  for i in range(1,g.n): # Find all the edges of the minimum spanning tree  min = INF # use INF Not connected ( The weight is infinite ) k = -1 # use -1 Indicates that the edge does not exist  for j in range(g.n): # Find out the distance from ( Pick vertex set )U Nearest vertex k if lowcost[j] != 0 and lowcost[j]<min: # If the weight of the selected edge is less than the value in the corresponding vertex list  min = lowcost[j] # Then update the array ( Shortest path ) The value is the weight of the edge  k = j # k Record the number of the smallest vertex  print("(%d,%d):%d"%(closest[k],k,+min),end='') # Output the edges of the minimum spanning tree  lowcost[k] = 0 # to update lowcost Array to record changes  for j in range(g.n): # Find the minimum distance array  if lowcost[j] != 0 and g.edges[k][j] < lowcost[j]: # Determine the minimum weight  lowcost[j] = g.edges[k][j] # modify lowcost closest[j] = k # modify closestif __name__ == '__main__':

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved