-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra.py
36 lines (31 loc) · 1.26 KB
/
dijkstra.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#dijkstra
from pythonds.graphs import Graph, PriorityQueue, Vertex
def dijkstra(graph,start):
start.setDistance(0)
pq =PriorityQueue()
pq.buildHeap([(aVertex.getDistance(),aVertex) for aVertex in graph])
while pq.size() > 0:
currentVert = pq.delMin()
for nextVert in currentVert.getConnections():
newDist = currentVert.getDistance() + currentVert.getWeight(nextVert)
if newDist < nextVert.getDistance():
nextVert.setDistance(newDist)
nextVert.setPred(currentVert)
pq.decreaseKey(nextVert, newDist)
#prim's algorithm
def prim(graph,start):
pq = PriorityQueue()
for v in graph:
v.setDistance(sys.maxsize)
v.setPred(None)
start.setDistance(0)
pq.buildHeap([(v.getDistance(),v) for v in graph])
while not pq.isEmpty():
currentVert = pq.delMin()
currentVert.setVisited(1)
for nextVert in currentVert.getConnections():
newCost = currentVert.getDistance() + currentVert.getWeight(nextVert)
if nextVert.getVisited() ==0 and newCost < nextVert.getDistance():
nextVert.setPred(currentVert)
nextVert.setDistance(newCost)
pq.decreaseKey(nextVert,newCost)