def dijkstra(graph, source): '''Apply the Dijkstra algorithm and return the a list where each position represents a vertice and its content represents the predecessor''' vertices = [] #list of vertices Q = PriorityQueue() #priority queue #fills 'vertices' and 'Q', each vertex receive the distance iquals infinity for v in range(len(graph)): vertices.append(Vertex(v)) Q.add_with_priority(v, vertices[v].dist) #the source vertex receive the distance zero vertices[source] = Vertex(num=source, dist=0) Q.decrease_priority(source, 0) while len(Q) != 0: u = Q.extract_min() for neighbor in get_adjacent(graph, u.num): alt = graph[u.num][neighbor] + u.dist Alt = Vertex(neighbor, alt) if vertices[neighbor].greater_than(Alt): vertices[neighbor].dist = alt vertices[neighbor].prev = u.num Q.decrease_priority(neighbor, alt) return [v.prev for v in vertices]
def Prim(self): from PriorityQueue import PriorityQueue import sys pq = PriorityQueue() # put all nodes in the pq for i in range(self._nNodes): pq.push((sys.maxsize,i)) # used to store the results start = [-1] * self._nNodes weight = [sys.maxsize] * self._nNodes # to save memory self._graph.adj[start[dest]][dest]['weight'] # the first node should be added to _mst anyhow pq.decrease_priority(0, 0) weight[0] = 0 # grow the _mst until there is no vertice in pq while pq.size() > 0: # get the cheapest node src = pq.pop()[1] for dest in list(nx.neighbors(self._graph, src)): if pq.contain(dest) and pq.priority(dest) > self._graph.adj[src][dest]['weight']: weight[dest] = self._graph.adj[src][dest]['weight'] start[dest] = src pq.decrease_priority(dest, weight[dest]) self._mst.clear() # print(list(self._mst.edges())) for dest in range(self._nNodes): if start[dest] != -1: self._mst.addEdge(start[dest], dest, weight[dest]) return self._mst