用python实现最小生成树--Prim算法

PS:如果进来是找《用matlab画散点图,并指定点与点之间的连线》这篇文章的,请进这个链接:https://blog.csdn.net/heavenmark/article/details/82794488

一、从Excel导入邻接矩阵

import xlrd
import sys

def matrix(address):                           #读取excel生成邻接矩阵
    wb = xlrd.open_workbook(address)
    sheet1 = wb.sheet_by_name('邻接矩阵_距离')
    L = []
    for i in range(1,13):
        a = sheet1.row_values(i)
        a.remove(a[0])
        L.append([int(x) for x in a])
    # print(L)
    return L

二、实现最小生成树

import matrix
import sys

def get_tree(primgraph,chararray):
    charlist = []
    charlist.append(chararray[0])
    mid = []    #mid[i]表示生成树集合中与点i最近的点的编号
    lowcost = []    #lowcost[i]表示生成树集合中与点i最近的点构成的边最小权值 ,-1表示i已经在生成树集合中
    lowcost.append(-1)
    mid.append(0)
    n = len(chararray)
    for i in range(1,n): #初始化mid数组和lowcost数组
        lowcost.append(primgraph[0][i])
        mid.append(0)
    sum = 0
    List = []
    MAX = sys.maxsize
   # MAX = 0
    for _ in range(1,n): #插入n-1个结点
        minid = 0
        min = MAX
        for j in range(1,n):  #寻找每次插入生成树的权值最小的结点
            if(lowcost[j]!=-1 and lowcost[j]primgraph[minid][j]):
                lowcost[j] = primgraph[minid][j]
                mid[j] = minid
    print(List)
    print("sum="+str(sum))
    print("插入结点顺序:"+str(charlist))
    return List


if __name__ == '__main__':
    address = 'C:/Users/Administrator/Desktop/b题基础数据.xlsx'
    chararray = ['A','B','C','D','E','F','G','H','I','J','K','L']
    pop=[2,1,6,16,30,9,9,10,14,21,24,11]      #各城市人口
    #pop=[24,3,47,82,30,38,95,59,110,21,24,38]   #各省份人口
    primgraph = matrix.matrix_valule(address,pop)     #计算网络价值的邻接矩阵
    get_tree(primgraph,chararray)

三、执行结果
用python实现最小生成树--Prim算法_第1张图片

你可能感兴趣的:(python,算法,数据处理与分析,python学习)