def __init__(self, EG): self._edgeTo = [-1 for _ in range(EG.V())] self._distTo = [_INF for _ in range(EG.V())] self._distTo[0] = 0 self._pq = IndexMinPQ(EG.V()) self._mst = [] # list of edges in MST self._weight = 0 self._marked = set() # set of vertices in MST self._pq.insert(0, 0) while (not self._pq.isEmpty() and len(self._mst) < EG.V() - 1): v = self._pq.delMin() if v > 0: self._mst.append(self._edgeTo[v]) self._weight += self._edgeTo[v].weight() self._visit(EG, v)
def __init__(self, G, s, t=None): "find the shortest path tree (in a directed graph with non-negative weights) from s to every other vertex using Dijkstra's alg" self._s = s self._distTo = [_INF for _ in range(G.V())] self._distTo[s] = 0 self._edgeTo = [_SENTINEL for _ in range(G.V()) ] # edgeTo[v]: last edge on shortest path from s to v self._pq = IndexMinPQ(G.V()) self._pq.insert(s, 0) while (not self._pq.isEmpty()): v = self._pq.delMin() # add closest vertex to source to Tree if t and v == t: return for e in G.adj(v): self._relax( e ) # relax(e) updates the distTo and edgeTo data structures