Python 用邻接表表示最小生成树
我一直在努力为班级解决一个问题。问题是: 给定一个无向图G,求G中的最小生成树 为了通过这个问题,我的函数必须接受并返回一个邻接列表。但是,我不知道如何将输入和输出表示为邻接列表Python 用邻接表表示最小生成树,python,algorithm,graph,minimum-spanning-tree,kruskals-algorithm,Python,Algorithm,Graph,Minimum Spanning Tree,Kruskals Algorithm,我一直在努力为班级解决一个问题。问题是: 给定一个无向图G,求G中的最小生成树 为了通过这个问题,我的函数必须接受并返回一个邻接列表。但是,我不知道如何将输入和输出表示为邻接列表 from collections import defaultdict class Graph: def __init__(self,vertices): self.V= vertices self.graph = [] def Edge(self,u,v,w):
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---
"""
从集合导入defaultdict
类图:
定义初始化(自身,顶点):
self.V=顶点
self.graph=[]
def边缘(自身、u、v、w):
self.graph.append([u,v,w])
#查找元素i集合的实用函数
def find(自我、家长、i):
如果父项[i]==i:
返回i
返回self.find(父,父[i])
#两组x和y并集的函数
def联合(自身、父级、等级、x、y):
xroot=self.find(父级,x)
yroot=self.find(父级,y)
#将小秩树附加到高秩树的根下
如果秩[xroot]<秩[yroot]:
父[xroot]=yroot
elif秩[xroot]>秩[yroot]:
父[yroot]=xroot
#如果秩相同,则将1作为根并按1递增秩
其他:
父[yroot]=xroot
秩[xroot]+=1
#构建MST的主要功能
def问题3(G):
MST=[]#这将存储MST
e=0#用于MST[]的索引变量
i=0#排序边的索引变量
G.graph=已排序(G.graph,key=lambda项:项[2])
父项=[];排名=[]
#使用单个图元创建V子集
对于范围内的节点(G.V):
parent.append(节点)
秩.追加(0)
#要获取的边等于V-1
当e
假设您将最小生成树计算为称为MST的边列表。现在,MST包含三个(u,v,weight)
。您可以做的是在MST中的边上迭代,并为每个这样的边(u,v,weight)
将一个元组(v,weight)
附加到u
的邻接列表中,还将一个元组(u,weight)
附加到v
的邻接列表中。在伪代码中,它可能如下所示:
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))
假设您将最小生成树计算为称为MST的边列表。现在,MST包含三个
(u,v,weight)
。您可以做的是在MST中的边上迭代,并为每个这样的边(u,v,weight)
将一个元组(v,weight)
附加到u
的邻接列表中,还将一个元组(u,weight)
附加到v
的邻接列表中。在伪代码中,它可能如下所示:
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))
您可以使用一个正方形矩阵来表示邻接关系,每个节点有一行/一列-1s表示邻接关系,0表示非邻接关系。@barny这将是一个邻接矩阵,而不是列表。不同的运行时间/存储成本有所不同。然而,对于这个问题,我建议使用一个矩阵而不是一个列表。这就是问题的关键,问题明确指出我必须使用一个邻接列表。这一点很好。假设节点编号为0到N-1,则邻接列表有N个条目,每个条目都可能是所有相邻节点的空列表。简单。或者每个条目都可以是一组相邻节点的编号,所以基本上我只需要将边列表转换成邻接列表?例如,我在原始问题中使用提示列表,并使用它代替每个单独的g.Edge。使用
g.Edge={'A':[('B',2)],'B':[('A',2),('C',5)],'C':[('B',5)]}
不会显示任何内容。所以我猜我必须修改我的边函数。你可以用一个正方形矩阵来表示邻接,每个节点有一行/一列-1s表示邻接,0表示不邻接。@barny那将是一个邻接矩阵,而不是列表。不同的运行时间/存储成本有所不同。然而,对于这个问题,我建议使用一个矩阵而不是一个列表。这就是问题的关键,问题明确指出我必须使用一个邻接列表。这一点很好。假设节点编号为0到N-1,则邻接列表有N个条目,每个条目都可能是所有相邻节点的空列表。简单。或者每个条目都可以是一组相邻节点的编号,所以基本上我只需要将边列表转换成邻接列表?例如,我在原始问题中使用提示列表,并使用它代替每个单独的g.Edge。使用g.Edge={'A':[('B',2)],'B':[('A',2),('C',5)],'C':[('B',5)]}
不会显示任何内容。所以我猜我将不得不修改我的边函数