Skip to content

Instantly share code, notes, and snippets.

@zhuangh
Created January 30, 2018 00:02
Show Gist options
  • Save zhuangh/457b847be7953230fd8604896c4e512d to your computer and use it in GitHub Desktop.
Save zhuangh/457b847be7953230fd8604896c4e512d to your computer and use it in GitHub Desktop.
Kruskal method
def union_find(u, arr):
if arr[u] == u:
return u
return union_find(arr[u], arr)
def union(u, v, arr):
arr[union_find(v, arr)] = union_find(u, arr)
def kruskal(nodes, edges):
mst = []
edges = sorted(edges, key=lambda e: e[2])
arr = [i for i in range(0, len(nodes))]
base = ord('A') # for indexing the vertice
for e in edges:
u, v, w = e
u = int(ord(u) - base)
v = int(ord(v) - base)
if union_find(u, arr) != union_find(v, arr):
mst.append(e)
union(u, v, arr)
return mst
#test
nodes = list("ABCDEFG")
edges = [ ("A", "B", 7), ("A", "D", 5),
("B", "C", 8), ("B", "D", 9), ("B", "E", 7),
("C", "E", 5),
("D", "E", 15), ("D", "F", 6),
("E", "F", 8), ("E", "G", 9),
("F", "G", 11)]
print("kruskal:", kruskal(nodes, edges))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment