def dijkstra(source, graph): pQueue = PriorityQueue() graph[source]['dist'] = 0 for v in graph: pQueue.enqueue((graph[v]['dist'], v)) while not pQueue.isEmpty(): u = pQueue.dequeue() baseDist = graph[u]['dist'] print('Visiting',u, 'at distance', baseDist) print('Edges from this vertex', graph[u]['edgeTo']) for w in graph[u]['edgeTo']: edgeLen = graph[u]['edgeTo'][w] newDist = baseDist + edgeLen currentDist = graph[w]['dist'] if newDist < currentDist: graph[w]['dist'] = newDist print('Distance to', w, 'set to', baseDist, '+', edgeLen, '=', newDist) pQueue.changePriority(w, newDist) print() # Print the results print('Final result: distances of all vertices from ' + source) distancesList = [] for v in graph: distancesList.append((v, graph[v]['dist'])) print(distancesList)
def prim(first, graph): pQueue = PriorityQueue() graph[first]['dist'] = 0 for i in graph: pQueue.enqueue((graph[i]['dist'], i)) mst = [] # dictionary to record for each vertex in the queue its nearest vertex in the tree nearestInTreeTo = {} print('Removing front item', first, 'from priority queue') while not pQueue.isEmpty(): u = pQueue.dequeue() print('Inspecting neighbours of vertex', u) for w in graph[u]['edgeTo']: edgeLen = graph[u]['edgeTo'][w] print(u, 'to', w,':', edgeLen) currentDist = graph[w]['dist'] if w in pQueue and edgeLen < currentDist: graph[w]['dist'] = edgeLen pQueue.changePriority(w, edgeLen) nearestInTreeTo[w] = u if not pQueue.isEmpty(): print('PriorityQueue is now :', pQueue.getEntries()) print() nextVertex = pQueue.peek() print('Next vertex is:', nextVertex) weight = graph[nextVertex]['dist'] newEdge = [[(nearestInTreeTo[nextVertex], nextVertex), weight]] print('Nearest in tree to', nextVertex,'is', nearestInTreeTo[nextVertex]) print('Adding', newEdge, 'to the tree') mst = mst + [[(nearestInTreeTo[nextVertex], nextVertex), weight]] print('Tree is now :', mst) print() print('Removing front item', nextVertex, 'from priority queue') print('MST completed') return mst