Пример #1
0
class Dijkstra(object):
    def __init__(self):
        self.infinity = 1000000
        self.shortestPathTo = {}
        self.edgeTo = {}
        self.minQueue = MinPriorityQueue()
    
    def __initSingleSource(self, graph, startNode):
        self.shortestPathTo = dict.fromkeys(graph, self.infinity)
        self.edgeTo = dict.fromkeys(graph, None)
        self.shortestPathTo[startNode] = 0
        
    def findShortestPaths(self, graph, startNode):
        self.__initSingleSource(graph, startNode)
        self.minQueue.insert((self.shortestPathTo[startNode], startNode))
        
        while not self.minQueue.empty():
            dist, node = self.minQueue.extractMin()
            self.__relaxation(graph, node)
        return self.shortestPathTo, self.edgeTo
            
    def __relaxation(self, graph, node):
        for adjacentNode in graph[node]:
            edgeDistance = graph[node][adjacentNode]
            overallDistance = self.shortestPathTo[node] + edgeDistance
            if self.shortestPathTo[adjacentNode] > overallDistance:
                self.shortestPathTo[adjacentNode] = overallDistance
                self.edgeTo[adjacentNode] = node
                
                if self.minQueue.contains(adjacentNode):
                    self.minQueue.decreaseKey(self.shortestPathTo[adjacentNode], adjacentNode)
                else:
                    self.minQueue.insert((self.shortestPathTo[adjacentNode], adjacentNode))
Пример #2
0
 def __init__(self):
     self.infinity = 1000000
     self.shortestPathTo = {}
     self.edgeTo = {}
     self.minQueue = MinPriorityQueue()