Advertisement
makispaiktis

Greedy Algorithms - Kruskal

May 27th, 2020 (edited)
1,242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.86 KB | None | 0 0
  1. def kruskal(edges):
  2.     sorted_edges = sorted(edges, key=lambda edge: edge[2])
  3.  
  4.     # Αντιστοιχίζω κάθε κορυφή σε κενό σετ/σύνολο
  5.     # Και μετά, θα προσθέσω στο σετ την ίδια κορυφή
  6.     # {A: A, B: B, C: C, ....}
  7.     subgraph_node = dict()
  8.     for u, v, weight in sorted_edges:
  9.         subgraph_node[u] = set()
  10.         subgraph_node[v] = set()
  11.     for u in subgraph_node:
  12.         subgraph_node[u].add(u)
  13.  
  14.     is_included_in_mst = list()
  15.  
  16.     for u, v, weight in sorted_edges:
  17.         if subgraph_node[u] == subgraph_node[v]:
  18.             is_included_in_mst.append(False)
  19.         else:
  20.             is_included_in_mst.append(True)
  21.             # Ενώνω
  22.             combined_subgraph = set.union(subgraph_node[u], subgraph_node[v])
  23.             # Κάθε κορυφή του λεξικού πλέον αντιστοιχίζεται σε ένα σετ/σύνολο,
  24.             # το οποίο περιέχει το υπόλοιπο δένδρο/γράφο στον οποίο ανήκει η κορυφή αυτή
  25.             for k in combined_subgraph:
  26.                 subgraph_node[k] = combined_subgraph
  27.  
  28.     return is_included_in_mst, sorted_edges
  29.  
  30.  
  31. def visualize(edges, colors):
  32.     from pyvis.network import Network
  33.     net = Network()
  34.     edges = [(edges[i][0], edges[i][1], edges[i][2], colors[i]) for i in range(len(edges))]
  35.     for u, v, weight, color in edges:
  36.         net.add_node(u)
  37.         net.add_node(v)
  38.         net.add_edge(u, v, label=str(weight), color=color)
  39.  
  40.     net.show('network.html')
  41.  
  42.  
  43. edges = [('A', 'B', 1), ('B', 'C', 4), ('B', 'D', 2), ('C', 'D', 6), ('A', 'D', 3)]
  44.  
  45. # visualize(edges,colors)
  46. is_included_in_mst, sorted_edges = kruskal(edges)
  47. colors = ['red' if is_included else 'blue' for is_included in is_included_in_mst]
  48. visualize(sorted_edges, colors)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement