Exemple #1
0
    def dijkstra(self, graph, source):
        """Dijkstra

        This method computes shortest distance and path for each node
        from the source node, and save results in each node's distance
        attribute.
        return None
        """
        reachable = self.preprocessing(graph, source)
        self.dists[source.id] = 0
        self.paths[source.id] = source.id
        unknown = HashHeap(
            key=lambda x, y: self.dists[x.id] < self.dists[y.id])
        for node_id in reachable:
            unknown.add(graph[node_id])  # add to unknown
        marked = [False] * len(graph)

        while unknown:
            node = unknown.pop()
            marked[node.id] = True
            for edge in node.edges:
                adj = graph[edge.head]
                if (not marked[adj.id] and
                    self.dists[node.id] + edge.dist < self.dists[adj.id]):
                    self.dists[adj.id] = self.dists[node.id] + edge.dist
                    unknown.update(adj)  # method only in hash heap
                    self.paths[adj.id] = node.id