Skip to content

Instantly share code, notes, and snippets.

@cgearhart
Created March 31, 2014 16:54
Show Gist options
  • Save cgearhart/9896763 to your computer and use it in GitHub Desktop.
Save cgearhart/9896763 to your computer and use it in GitHub Desktop.
Prim's Algorithm - Find MST of an undirected, arbitrarily connected graph
def mst(graph):
'''
mst retuns the minimum spanning tree of `graph`, which must be a symmetric NxN array, where
element (i,j) is the weight of the connection from node i to node j. The diagonal should be all
zeros (because i and j are the same point), and unconnected nodes are `None`.
The nth position of the array returned contains the parent node of node n. The order always
starts from node 0 as the root of the tree, so order[0] is always None.
'''
order = [None] * len(graph)
parents = [0] * len(graph)
choices = graph[0]
for _ in xrange(1, len(graph)):
i, v = 0, 0
for j, w in enumerate(choices):
if w > 0 and (v == 0 or w < v):
i, v = j, w
order[i] = parents[i]
for j, w in enumerate(graph[i]):
if w is not None and w < choices[j]:
choices[j], parents[j] = w, i
return order
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment