Advertisement
valentina_cobo

Untitled

Dec 17th, 2021
1,594
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. class Graph:
  2.  
  3.     def __init__(self, vertex):
  4.         self.V = vertex
  5.         self.graph = []
  6.  
  7.     def add_edge(self, u, v, w):
  8.         self.graph.append([u, v, w])
  9.  
  10.  
  11.     def search(self, parent, i):
  12.         if parent[i] == i:
  13.             return i
  14.         return self.search(parent, parent[i])
  15.  
  16.     def apply_union(self, parent, rank, x, y):
  17.         xroot = self.search(parent, x)
  18.         yroot = self.search(parent, y)
  19.         if rank[xroot] < rank[yroot]:
  20.             parent[xroot] = yroot
  21.         elif rank[xroot] > rank[yroot]:
  22.             parent[yroot] = xroot
  23.         else:
  24.             parent[yroot] = xroot
  25.             rank[xroot] += 1
  26.  
  27.  
  28.     def kruskal(self):
  29.         result = []
  30.         i, e = 0, 0
  31.         self.graph = sorted(self.graph, key=lambda item: item[2])
  32.         parent = []
  33.         rank = []
  34.         for node in range(self.V):
  35.             parent.append(node)
  36.             rank.append(0)
  37.         while e < self.V - 1:
  38.             u, v, w = self.graph[i]
  39.             i = i + 1
  40.             x = self.search(parent, u)
  41.             y = self.search(parent, v)
  42.             if x != y:
  43.                 e = e + 1
  44.                 result.append([u, v, w])
  45.                 self.apply_union(parent, rank, x, y)
  46.         for u, v, weight in result:
  47.             print("Edge:",u, v,end =" ")
  48.             print("-",weight)
  49.  
  50.  
  51. lista = [[0,4,5,0],
  52.      [4,0,0,2],
  53.      [5,0,0,6],
  54.      [0,2,6,0]]
  55.    
  56. def matriz_grafo (l):
  57.     g2 = Graph(len(l))
  58.     for i in range(len(l)):
  59.         for j in range(len(l)):
  60.             if l[i][j]!= 0:
  61.                 g2.add_edge(i,j,l[i][j])
  62.     g2.kruskal()
  63.  
  64.  
  65. matriz_grafo(lista)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement