Prim的算法替代解决方案

时间:2019-10-12 16:52:04

标签: python minimum-spanning-tree prims-algorithm

我正在尝试为给定的图查找备用生成树。但是,我不明白如何在输出中一起使用多个解决方案。

对于给定的图,在输出中,我得到0-2,权重为8。此外,1-3的权重为8。所以我也想要一棵单独的生成树,其一部分为1-3解决方案,给我2个单独的解决方案。

import sys 
class Graph(): 

    def __init__(self, vertices): 
        self.V = vertices 
        self.graph = [[0 for column in range(vertices)]for row in range(vertices)] 

    def printTree(self, parent): 
        print ("Edge \t Weight")
        for i in range(1, self.V): 
            print (parent[i], "-", i, "\t", self.graph[i][ parent[i] ] )

    def minKey(self, key, Set): 
        min = sys.maxsize 
        for v in range(self.V): 
            if key[v] < min and Set[v] == False: 
                min = key[v] 
                min_index = v 
        return min_index 

# Prim's Algorithm 
    def prim(self): 

        key = [sys.maxsize] * self.V # Key values used to pick minimum weight edge
        parent = [None] * self.V  # Array to store constructed MST 
        key[0] = 0                # Make key 0 so that this vertex is picked as first vertex
        Set = [False] * self.V # Initially there are no vertices in MST set
        parent[0] = -1            # First node is always the root 

        for i in range(self.V):                 
            u = self.minKey(key, Set)                                            
            Set[u] = True 

            for v in range(self.V): 
                if self.graph[u][v] > 0 and Set[v] == False and key[v] > self.graph[u][v]: 
                        key[v] = self.graph[u][v] 
                        parent[v] = u 

        self.printTree(parent) 


Prim = Graph(7) 
Prim.graph = [[0, 4, 8, 0, 0, 0, 0], 
              [4, 0, 9, 8, 10,0, 0], 
              [8, 9, 0, 2, 0, 1, 0], 
              [0, 8, 2, 0, 7, 9, 0], 
              [0, 10, 0, 7, 0, 5, 6],
              [0, 0, 1, 9, 5, 0, 2],
              [0, 0, 0, 0, 6, 2, 0]]
Prim.prim()

0 个答案:

没有答案