コード例 #1
0
    def mst_prim(self, r=0):
        """Returns the set of edges in some
        minimum spanning tree (MST) of the graph,
        computed using Prim's algorithm.

        Keyword arguments:
        r - vertex id to designate as the root (default is 0).
        """

        parent = [None for x in range(len(self._adj))]
        Q = PQ()
        Q.add(r, 0)
        for u in range(len(self._adj)):
            if u != r:
                Q.add(u, math.inf)
        while not Q.is_empty():
            u = Q.extract_min()
            for v, w in self._adj[u].__iter__(True):
                if Q.contains(v) and w < Q.get_priority(v):
                    parent[v] = u
                    Q.change_priority(v, w)
        A = set()
        for v, u in enumerate(parent):
            if u != None:
                A.add((u, v))
                # A = A | {(u,v)}
        return A
コード例 #2
0
    def dijkstras_version_2(self, s):
        """Dijkstra's Algorithm using a binary heap as the PQ."""

        # Programming Assignment 3:
        # 3) Implement Dijkstra's Algorithm using a binary heap implementation of a PQ as the PQ.
        #    Specifically, use the implementation I have posted here: https://github.com/cicirello/PythonDataStructuresLibrary
        #    Use the download link (if you simply click pq.py Github will just show you the source in a web browser with line numbers).
        #
        #    Have this method return a list of 3-tuples, one for each vertex, such that first position is vertex id,
        #    second is distance from source vertex (i.e., what pseudocode from textbook refers to as v.d), and third
        #    is the vertex's parent (what the textbook refers to as v.pi).  E.g., (2, 10, 5) would mean the shortest path
        #    from s to 2 has weight 10, and vertex 2's parent is vertex 5.
        #
        #    the parameter s is the source vertex.
        distance = [math.inf for x in self._adj]
        parent = [None for x in self._adj]
        Q = PQ()
        distance[s] = 0
        Q.add(s, 0)
        S = []
        for u in range(len(self._adj)):
            if u != s:
                Q.add(u, math.inf)
        while not Q.is_empty():
            u = Q.extract_min()
            S.append(u)
            for v, w in self._adj[u].__iter__(True):
                if (distance[u] + w) < distance[v]:
                    parent[v] = u
                    distance[v] = (distance[u] + w)
        returnlist = []
        for v in S:
            returnlist.append((v, distance[v], parent[v]))
        return returnlist
コード例 #3
0
    def dijkstra(self,s):
        """Dijkstra's Algorithm using a binary heap as the PQ.

        Keyword Arguments:
        s - The source vertex.
        """

        # Programming Assignment 3:
        # 2) Implement Dijkstra's Algorithm using a binary heap implementation of a PQ as the PQ.
        
        pointers = [None for i in range(len(self._adj))]
        costs = [math.inf for i in range(len(self._adj))]
        pointers[s]=s
        costs[s]=0

        S = set()
        Q = PQ()
        
        #Q = G.V
        for i in range(len(self._adj)):
            Q.add(i,costs[i])

        while(not Q.is_empty()):
            u = Q.extract_min()
            S = S | {u}
            for v in self._adj[u].__iter__(True):
                #relax
                if v[1]+costs[u] < costs[v[0]]:
                    costs[v[0]] = v[1]+costs[u]
                    pointers[v[0]]=u
                    Q.change_priority(v[0],costs[v[0]])

        return [(i,costs[i],pointers[i]) for i in range(len(self._adj))]
コード例 #4
0
ファイル: graphs.py プロジェクト: huyvuq/DS2-Graph-HuyVu
    def DijkstrasVersion2(self, sourceVertex):
        sourceVertex.distance = 0
        binaryHeap = PQ()
        binaryHeap.add(sourceVertex, sourceVertex.value)

        while not binaryHeap.is_empty():
            tempVertex = binaryHeap.peek_min()

            for e in tempVertex.edges:
                v = e.neighbor
                newDistance = tempVertex.distance + e.weight

                if newDistance < v.distance:
                    v.distance = newDistance
                    v.pred = tempVertex
                    binaryHeap.add(v, v.value)
            binaryHeap.extract_min()

        paths = []
        for v in self.vertices:
            paths.append((v.value, v.distance, v.pred))
        return paths
コード例 #5
0
    def dijkstra(self, s):
        """Dijkstra's Algorithm using a binary heap as the PQ.

        Keyword Arguments:
        s - The source vertex.
        """
        class VertexData:
            __slots__ = ['d', 'pred']

            def __init__(self):
                self.d = math.inf
                self.pred = None

        vertices = [VertexData() for i in range(len(self._adj))]

        #INIT SINGLE-SOURCE
        vertices[s].d = 0
        tuples = []
        S = []
        Q = PQ()

        for u in range(len(self._adj)):
            if u is s:
                Q.add(s, 0)
            else:
                Q.add(u, math.inf)
        while not Q.is_empty():
            u = Q.extract_min()
            S.append(u)
            for v, w in self._adj[u].__iter__(True):
                #RELAX
                if vertices[v].d > vertices[u].d + w:
                    vertices[v].d = vertices[u].d + w
                    vertices[v].pred = vertices[u]
        for u in S:
            if vertices[u].pred is None:
                tuples.append((u, vertices[u].d, None))
            else:
                tuples.append(
                    (u, vertices[u].d, vertices.index(vertices[u].pred)))
        return tuples
コード例 #6
0
ファイル: graph.py プロジェクト: Flouzr/Dijkstra-Bellman-Ford
    def dijkstra(self,s) :
        """Dijkstra's Algorithm using a binary heap as the PQ.

        Keyword Arguments:
        s - The source vertex.
        """

        class VertexData:
            __slots__ = ['d', 'pred']

            def __init__(self):
                self.d = math.inf
                self.pred = None

        vertices = [VertexData() for i in range(len(self._adj))]

        vertices[s].d = 0

        Q = PQ()
        S = []
        list = []

        vertices[s].d = 0
        Q.add(s, 0)

        for u in range(len(self._adj)):
            if u != s:
                Q.add(u, math.inf)

        while not Q.is_empty():
            u = Q.extract_min()
            S.append(u)
            for v, w in self._adj[u].__iter__(True):
                if (vertices[u].d + w) < vertices[v].d:
                    vertices[v].pred = u
                    vertices[v].d = (vertices[u].d + w)

        for v in S:
            list.append((v, vertices[v].d, vertices[v].pred))

        return list
コード例 #7
0
 def DijkstrasVersion2(self,s) :
     S = PQ()
     TL = []
     class VertexData :
         pass
     vertices = [VertexData() for i in range(len(self._adj))]
     for i in range(len(vertices)) :
         vertices[i].d = inf
         vertices[i].pred = -1
         S.add(i, vertices[i].d)
     vertices[s].d = 0
     vertices[s].pred = -1
     while not S.is_empty() :
         u = S.extract_min()
         
         TL.append((u, vertices[u].d, vertices[u].pred))
         for i in self._adj[u]:
             distance = vertices[u].d + self._w[(u,i)]
             if(distance < vertices[i].d):
                 vertices[i].d = distance
                 vertices[i].pred = u
                 S.change_priority(i, distance)
     return TL
コード例 #8
0
 def DijkstrasVersion2(self,s) :
     class VertexData:
         pass
     vList = [VertexData() for i in range(len(self._adj))]
     S = list()
     Q = PQ()
     vList[s].dist = 0
     vList[s].prev = None
     for v in range(len(vList)):
         if(v != s):
             vList[v].dist = float('inf')
             vList[v].prev = None
         Q.add(v, vList[v].dist)
     while not Q.is_empty():
         u = Q.extract_min()
         S.append((u, vList[u].dist, vList[u].prev))
         for v in self._adj[u]:
             temp = vList[u].dist + self._w[(u,v)]
             if temp < vList[v].dist:
                 vList[v].dist = temp
                 vList[v].prev = u
                 Q.change_priority(v, temp)
     return S