0

我一直在試圖解決類的問題。問題是:使用鄰接表來表示最小生成樹

給定一個無向圖,發現內的最小生成樹。

爲了通過這個問題,我的函數必須採取,並返回,一鄰接表。但是,我不確定如何去將輸入和輸出表示爲鄰接列表。

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--- 
""" 
+1

您可以使用具有每個節點的行/列的方陣來表示鄰接 - 鄰接爲1,非爲0則爲0。 – barny

+1

@barny這將是一個鄰接矩陣,而不是列表。各種運行時間/存儲成本存在差異。不過,我建議使用矩陣而不是列表來解決這個問題。 –

+0

多數民衆贊成的事情,這個問題明確表示,我不得不使用鄰接表。 – NoOrangeJuice

回答

2

假設您將最小生成樹計算爲稱爲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))