Skip to content

Instantly share code, notes, and snippets.

@mikezink

mikezink/prim.py Secret

Last active October 22, 2020 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikezink/3dc267d0cc6b8bdd56e10fad6d7febbe to your computer and use it in GitHub Desktop.
Save mikezink/3dc267d0cc6b8bdd56e10fad6d7febbe to your computer and use it in GitHub Desktop.
import sys
from pythonds.graphs import PriorityQueue, Graph, Vertex
def prim(G,start):
pq = PriorityQueue()
for v in G:
v.setDistance(sys.maxsize)
v.setPred(None)
start.setDistance(0)
pq.buildHeap([(v.getDistance(),v) for v in G])
while not pq.isEmpty():
currentVert = pq.delMin()
for nextVert in currentVert.getConnections():
newCost = currentVert.getWeight(nextVert)
if nextVert in pq and newCost<nextVert.getDistance():
nextVert.setPred(currentVert)
nextVert.setDistance(newCost)
pq.decreaseKey(nextVert,newCost)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment