Exemplo n.º 1
0
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n)

        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n)  #create the priority queue
        cur = self
        for i in range(0, self.n):  # Iterate through all vertex ID
            if (i == srcID):  # If ID is srcID
                pq.set(i, 0.0)  # Distance of srcID should be zero
            else:  # ID is not srcID
                pq.set(i, pq.Inf)  # Distance should be infinity

        d = {}  # Initialize the map with distances to nodes
        pi = {}  # Initialize the map with parents of vertices

        minKey, minDist = pq.extractMin()

        d[minKey] = minDist  #set orignal source distance to 0
        pi[minKey] = minKey  #set sources to orginal source

        while (pq.isEmpty() == False):  # COMPLETE the Dijkstra code here

            lst = self.adjList[
                minKey]  #grap array of lists of format (vertices,weight) for node minKey
            for n in lst:  #loop through said list

                ##grap the next node attached to this node somehow
                dist = n[1] + minDist  #grab distance from list

                node = n[0]  #grab node from list
                if (pq.hasKey(node)
                    ):  #check if that nodes min dist has been found
                    if (
                            pq.get(node) > dist
                    ):  #check if path to the node from minKey is less then current path
                        pq.set(node,
                               dist)  #set the nodes distance in the queue
                        d[node] = dist  #set the nodes distance in the return array
                        pi[node] = minKey  #sets the nodes parents

            minKey, minDist = pq.extractMin(
            )  #extract next node dont need to extract last node as all the paths will be filled would probably work better in a do while loop

        return (d, pi)
Exemplo n.º 2
0
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n)

        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n) #create the priority queue
        cur=self
        for i in range(0,self.n): # Iterate through all vertex ID
            if ( i == srcID):     # If ID is srcID
                pq.set(i,0.0)     # Distance of srcID should be zero
            else:                 # ID is not srcID
                pq.set(i, pq.Inf) # Distance should be infinity
        
        d = {}  # Initialize the map with distances to nodes
        pi = {} # Initialize the map with parents of vertices

        minKey, minDist=pq.extractMin()

        d[minKey]=minDist #set orignal source distance to 0
        pi[minKey]=minKey #set sources to orginal source



        while(pq.isEmpty()==False):# COMPLETE the Dijkstra code here

                lst=self.adjList[minKey]#grap array of lists of format (vertices,weight) for node minKey
                for n in lst:#loop through said list
                        
                        ##grap the next node attached to this node somehow
                        dist=n[1]+minDist#grab distance from list

                        node=n[0] #grab node from list
                        if(pq.hasKey(node)):#check if that nodes min dist has been found
                                if(pq.get(node)>dist):#check if path to the node from minKey is less then current path
                                        pq.set(node,dist)#set the nodes distance in the queue
                                        d[node]=dist#set the nodes distance in the return array
                                        pi[node]=minKey#sets the nodes parents

                minKey, minDist=pq.extractMin()#extract next node dont need to extract last node as all the paths will be filled would probably work better in a do while loop
                        

            
        return (d,pi)
Exemplo n.º 3
0
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n) # ensure that srcID is between 0 and size of graph.
        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n) #create the priority queue
        
        for i in range(0,self.n): # Iterate through all vertex ID
            if  i == srcID:     # If ID is srcID
                pq.set(i, 0.0)     # Distance of srcID should be zero
            else:                 # ID is not srcID
                pq.set(i, pq.Inf) # Distance should be infinity
        
        d = {}  # Initialize the map with distances to nodes
        pi = {} # Initialize the map with parents of vertices

        while not pq.isEmpty():  # loop until priority queue is empty.
            (node, dist) = pq.extractMin() # extract smallest dist node.
            d[node] = dist # update dictionary with shortest distance.
            for (vertex, weight) in self.adjList[node]: # check the adjacency list of popped node.
                newDist = dist + weight # calculate new distance.
                if pq.hasKey(vertex): # if we haven't already popped the node in the adjacency list yet.
                    if newDist < pq.get(vertex): # check distance vs new calculated dist.
                        pq.set(vertex, newDist) # update priority queue.
                        pi[vertex] = node # update parent list.

        return (d, pi)
Exemplo n.º 4
0
def dijkstra(graphObj, startVertex):
    pq = PriorityQueue()

    for vertex in graphObj.getVertices():
        if vertex == startVertex:
            pq.insert([0, vertex])
            graphObj.verticesList[startVertex].distance = 0
        else:
            pq.insert([INFINITY, vertex])

    while(len(pq.pqueue)):
        currentVertex = pq.extractMin()

        if len(pq.pqueue) == 1:
            break

        # print(pq.pqueue, pq.lookup)
        for adjNode in graphObj.verticesList[currentVertex[1]].getConnections():
            newDistance = graphObj.verticesList[currentVertex[1]].distance + graphObj.verticesList[currentVertex[1]].adjList[adjNode]
            if newDistance < graphObj.verticesList[adjNode].distance:
                graphObj.verticesList[adjNode].distance = newDistance
                graphObj.verticesList[adjNode].predecessor = currentVertex[1]
                index = pq.lookup[adjNode]
                pq.decreaseKey(index, newDistance)

    return graphObj
Exemplo n.º 5
0
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n)
        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n) #create the priority queue

        for i in range(0,self.n): # Iterate through all vertex ID
            if ( i == srcID):     # If ID is srcID
                pq.set(i,0.0)     # Distance of srcID should be zero
            else:                 # ID is not srcID
                pq.set(i, pq.Inf) # Distance should be infinity

        d = {}  # Initialize the map with distances to nodes
        pi = {} # Initialize the map with parents of vertices

        d[srcID] = 0 # first node to dist map since while won't catch it.

        while not pq.isEmpty():
            min = pq.extractMin()
            # Look at neighbors
            for neighbor in self.adjList[min[0]]: # where neighbor has not yet been removed from pq?
                alt = min[1] + neighbor[1]
                if pq.hasKey(neighbor[0]) and alt < pq.get(neighbor[0]): # previously stored needs to be replayed
                    # Update distances and parents everywhere
                    pq.set(neighbor[0], alt)
                    d[neighbor[0]] = alt
                    pi[neighbor[0]] = min[0]
        return (d,pi)
Exemplo n.º 6
0
def prims(graphObj, start):
    pq = PriorityQueue()

    for vertex in graphObj.verticesList:
        if vertex == start:
            g.verticesList[vertex].distance = 0
            pq.insert([0, vertex])
            continue
        g.verticesList[vertex].distance = INFINITY
        pq.insert([INFINITY, vertex])

    while(len(pq.pqueue)):
        currentVertex = pq.extractMin()

        if len(pq.pqueue) == 1:
            return

        for adjNode in graphObj.verticesList[currentVertex[1]].getConnections():
            if adjNode in pq.lookup(adjNode):
                newDistance = graphObj.verticesList[currentVertex[1]].getCost(adjNode)
                if newDistance < graphObj.verticesList[adjNode].distance:
                    graphObj.verticesList[adjNode].distance = newDistance
                    graphObj.verticesList[adjNode].predecessor = currentVertex[1]

        return graphObj
Exemplo n.º 7
0
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n)
        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n)  #create the priority queue

        for i in range(0, self.n):  # Iterate through all vertex ID
            if (i == srcID):  # If ID is srcID
                pq.set(i, 0.0)  # Distance of srcID should be zero
            else:  # ID is not srcID
                pq.set(i, pq.Inf)  # Distance should be infinity

        d = {}  # Initialize the map with distances to nodes
        pi = {}  # Initialize the map with parents of vertices

        # COMPLETE the Dijkstra code here
        if srcID == None or self.adjList[
                srcID] == None:  #make sure srcId is not None
            return
        Dist = 0.0
        for i in range(0, self.n):  #iniatialize dictionaries to default values
            d[i] = pq.Inf
            pi[i] = i
        d[srcID] = 0.0  #set source to zero
        while (not pq.isEmpty()):  #check if the queue is empty
            j = pq.extractMin(
            )  #tuple of min distance and vertex. j = (vertex,minDist)
            for i in self.adjList[j[0]]:
                if pq.hasKey(
                        i[0]
                ):  #assertion of pq.get(i) is that i must be in the priority queue
                    if i[1] + j[1] < pq.get(
                            i[0]
                    ):  #if distance of prior two nodes is less than current distance
                        Dist = j[1] + i[1]
                        pq.set(i[0], Dist)  #update distance at vertex to Dist
                        pi[i[0]] = j[0]  #map vertex to its parent
                        d[i[0]] = Dist  #map vertex to its new distance
        return (d, pi)
Exemplo n.º 8
0
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n)
        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n)  #create the priority queue

        for i in range(0, self.n):  # Iterate through all vertex ID
            if (i == srcID):  # If ID is srcID
                pq.set(i, 0.0)  # Distance of srcID should be zero
            else:  # ID is not srcID
                pq.set(i, pq.Inf)  # Distance should be infinity

        d = {}  # Initialize the map with distances to nodes
        pi = {}  # Initialize the map with parents of vertices

        parent = None

        while not pq.isEmpty():
            minNode = pq.extractMin()
            if parent is None:
                d[minNode[0]] = minNode[1]
                pi[minNode[0]] = minNode[0]
            elif minNode[1] != pq.Inf:
                d[minNode[0]] = float(round(decimal.Decimal(minNode[1]), 2))
            else:
                d[minNode[0]] = pq.Inf

            lst = self.adjList[minNode[0]]
            for i in range(len(lst)):
                if pq.hasKey(lst[i][0]) and pq.get(
                        lst[i][0]) > lst[i][1] + d[minNode[0]]:
                    pi[lst[i][0]] = minNode[0]
                    pq.set(lst[i][0], lst[i][1] + d[minNode[0]])

            parent = minNode[0]

        return (d, pi)
Exemplo n.º 9
0
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n)
        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n) #create the priority queue

        for i in range(0,self.n): # Iterate through all vertex ID
            if ( i == srcID):     # If ID is srcID
                pq.set(i,0.0)     # Distance of srcID should be zero
            else:                 # ID is not srcID
                pq.set(i, pq.Inf) # Distance should be infinity

        d = {}  # Initialize the map with distances to nodes
        pi = {} # Initialize the map with parents of vertices

        parent = None

        while not pq.isEmpty():
            minNode = pq.extractMin()
            if parent is None:
                d[minNode[0]] = minNode[1]
                pi[minNode[0]] = minNode[0]
            elif minNode[1] != pq.Inf:
                d[minNode[0]] = float(round(decimal.Decimal(minNode[1]), 2))
            else:
                d[minNode[0]] = pq.Inf

            lst = self.adjList[minNode[0]]
            for i in range(len(lst)):
                if pq.hasKey(lst[i][0]) and pq.get(lst[i][0]) > lst[i][1] + d[minNode[0]]:
                    pi[lst[i][0]] = minNode[0]
                    pq.set(lst[i][0], lst[i][1] + d[minNode[0]])

            parent = minNode[0]

        return (d,pi)
Exemplo n.º 10
0
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n)
        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n) #create the priority queue
        
        for i in range(0,self.n): # Iterate through all vertex ID
            if ( i == srcID):     # If ID is srcID
                pq.set(i,0.0)     # Distance of srcID should be zero
            else:                 # ID is not srcID
                pq.set(i, pq.Inf) # Distance should be infinity
        
        d = {}  # Initialize the map with distances to nodes
        pi = {} # Initialize the map with parents of vertices
        
        # COMPLETE the Dijkstra code here
        
    # self.n : number of vertices in the graph
    # self.adjList: Adjacency list stored as a list of lists.
    #    self.adjList[i] stores all adjacent nodes to vertex ID i along with edge weights.
    # Eg., if vertex 2 has three edges (2,3) with weight 4.5, (2,4) with weight 3.2, and (2,5) with 2.1
    #    self.adjList[2] is the list [ (3,4.5), (4,3.2), (5,2.12) ]
    # your goal is to implement the singleSourceShortestPath function.
        while not pq.isEmpty():
            (n, dist) = pq.extractMin()
            d[n] = dist
            neighbors = self.adjList[n]
            for i in range (0, len(neighbors)):
                (v, e) = neighbors[i]
                if pq.hasKey(v):
                    oldDist = pq.get(v)		#is it more efficient if these constants are declared outside the loop?
                    newDist = dist + e
                    if newDist < oldDist:
                        pq.set(v, newDist)
                        pi[v] = n 
        return (d,pi)	
Exemplo n.º 11
0
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n
                )  # ensure that srcID is between 0 and size of graph.
        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n)  #create the priority queue

        for i in range(0, self.n):  # Iterate through all vertex ID
            if i == srcID:  # If ID is srcID
                pq.set(i, 0.0)  # Distance of srcID should be zero
            else:  # ID is not srcID
                pq.set(i, pq.Inf)  # Distance should be infinity

        d = {}  # Initialize the map with distances to nodes
        pi = {}  # Initialize the map with parents of vertices

        while not pq.isEmpty():  # loop until priority queue is empty.
            (node, dist) = pq.extractMin()  # extract smallest dist node.
            d[node] = dist  # update dictionary with shortest distance.
            for (vertex, weight) in self.adjList[
                    node]:  # check the adjacency list of popped node.
                newDist = dist + weight  # calculate new distance.
                if pq.hasKey(
                        vertex
                ):  # if we haven't already popped the node in the adjacency list yet.
                    if newDist < pq.get(
                            vertex):  # check distance vs new calculated dist.
                        pq.set(vertex, newDist)  # update priority queue.
                        pi[vertex] = node  # update parent list.

        return (d, pi)
Exemplo n.º 12
0
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n)
        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n)  #create the priority queue

        for i in range(0, self.n):  # Iterate through all vertex ID
            if (i == srcID):  # If ID is srcID
                pq.set(i, 0.0)  # Distance of srcID should be zero
            else:  # ID is not srcID
                pq.set(i, pq.Inf)  # Distance should be infinity

        d = {}  # Initialize the map with distances to nodes
        pi = {}  # Initialize the map with parents of vertices

        d[srcID] = 0  # first node to dist map since while won't catch it.

        while not pq.isEmpty():
            min = pq.extractMin()
            # Look at neighbors
            for neighbor in self.adjList[min[
                    0]]:  # where neighbor has not yet been removed from pq?
                alt = min[1] + neighbor[1]
                if pq.hasKey(neighbor[0]) and alt < pq.get(
                        neighbor[0]):  # previously stored needs to be replayed
                    # Update distances and parents everywhere
                    pq.set(neighbor[0], alt)
                    d[neighbor[0]] = alt
                    pi[neighbor[0]] = min[0]
        return (d, pi)
Exemplo n.º 13
0
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n)
        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n) #create the priority queue

        for i in range(0,self.n): # Iterate through all vertex ID
            if ( i == srcID):     # If ID is srcID
                pq.set(i,0.0)     # Distance of srcID should be zero
            else:                 # ID is not srcID
                pq.set(i, pq.Inf) # Distance should be infinity

        d = {}  # Initialize the map with distances to nodes
        pi = {} # Initialize the map with parents of vertices

        #Code Starts HERE

        d[srcID] = 0 #Set distances from source equal to 0
        pi[srcID] = None #Set parents to None

        while not pq.isEmpty(): #While the priority queue is not empty
            (currentVertex,currentDistance) = pq.extractMin() #Extract the Min
            for (nextVertex, weight) in self.adjList[currentVertex]:
                newDist = weight + currentDistance
                if pq.hasKey(nextVertex): #Check if nextVertex exists in priority queue
                    if newDist < pq.get(nextVertex): #If the new distance is less
                        d[nextVertex] = newDist #Set new distnace
                        pi[nextVertex] = currentVertex #Set the parents
                        pq.set(nextVertex,newDist) #Set the new distance for the vertex
        return (d,pi)