python - 使用邻接表表示最小生成树

标签 python algorithm graph minimum-spanning-tree kruskals-algorithm

我一直在尝试为类解决一个问题。问题是:

Given an undirected graph G, find the minimum spanning tree within G.

为了通过这个问题,我的函数必须接受并返回一个邻接表。但是,我不确定如何将输入和输出表示为邻接表。

from collections import defaultdict

class Graph:

    def __init__(self,vertices):
        self.V= vertices
        self.graph = []

    def Edge(self,u,v,w):
        self.graph.append([u,v,w])

    # A utility function to find set of an element i
    def find(self, parent, i):
        if parent[i] == i:
            return i
        return self.find(parent, parent[i])

    # A function that does union of two sets of x and y
    def union(self, parent, rank, x, y):
        xroot = self.find(parent, x)
        yroot = self.find(parent, y)

        # Attach smaller rank tree under root of high rank tree
        if rank[xroot] < rank[yroot]:
            parent[xroot] = yroot
        elif rank[xroot] > rank[yroot]:
            parent[yroot] = xroot
        # If ranks are same, then make one as root and increment rank by one
        else :
            parent[yroot] = xroot
            rank[xroot] += 1

    # The main function to build the MST
    def Question3(G):

        MST =[] # This will store the MST
        e = 0 # An index variable used for MST[]
        i = 0 # An index variable for sorted edges
        G.graph =  sorted(G.graph,key=lambda item: item[2])

        parent = [] ; rank = []

        # Create V subsets with single elements
        for node in range(G.V):
            parent.append(node)
            rank.append(0)

        # Edges to be taken is equal to V-1
        while e < G.V -1 :

            # Take smallest edge and increment the index
            u,v,w =  G.graph[i]
            i = i + 1
            x = G.find(parent, u)
            y = G.find(parent ,v)

            # If including this edge does't cause cycle, include it
            # in result and increment the index of result for next edge
            if x != y:
                e = e + 1
                MST.append([u,v,w])
                G.union(parent, rank, x, y)
            # Else discard the edge
        print "Minimum Spanning Tree"
        for u,v,weight  in MST:
            print ("%d -- %d == %d" % (u,v,weight))

g = Graph(4)
g.Edge(0, 1, 9)
g.Edge(0, 2, 6)
g.Edge(0, 3, 5)
g.Edge(1, 3, 12)
g.Edge(2, 3, 4)
g.Question3()
print """---End Question 3---
"""

最佳答案

假设您将最小生成树计算为称为 MST 的边列表。现在,MST 包含三元组 (u, v, weight)。您可以做的是迭代 MST 中的边,并为每个这样的边 (u, v, weight) 将元组 (v, weight) 附加到的邻接列表中u,并且还在v的邻接表中附加一个元组(u, weight)。在伪代码中它可能看起来像这样:

adj = {} # your resulting adjacency lists, one for each vertex in the graph
for u, v, weight in MST:
   if u not in adj:
      adj[u] = []
   adj[u].append((v, weight))
   if v not in adj:
      adj[v] = []
   adj[v].append((u, weight))

关于python - 使用邻接表表示最小生成树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43145679/

相关文章:

Python - NLTK 分隔标点符号

c++ - 有效地获取给定数字的所有除数

python - 使用 matplotlib 和 seaborn 生成并绘制高斯混合图

c++ - 显示深度优先搜索图遍历 C++

python - 将多列列表分解为行

python - celery 任务消失

image - 从多边形中移除不正确的像素

python - 区域生长算法

javascript - HighCharts:增加堆叠条形图的宽度和填充

python - 使用seaborn绘制热图时出现类型错误