コード例 #1
0
            path.append(p)
            v = p
        path.reverse()
        return path


if __name__ == "__main__":
    import graph_utils

    def report_results(G, s, bf):
        for v in range(G.V()):
            sp = ' -> '.join([str(x) for x in bf.path_to(v)])
            print "%d to %d (%.2f) %s" % (s, v, bf.path_length(v), sp)

    source = 0
    bf = BellmanFordShortestPath()

    # test graph with negative edges
    G = graph_utils.load_weighted_digraph('../data/tinyEWDNeg.txt', True)
    bf.shortest_path(G, source)
    report_results(G, source, bf)

    # test graph with negative cycle
    try:
        G = graph_utils.load_weighted_digraph('../data/tinyEWDNegCyc.txt', True)
        bf.shortest_path(G, source)
    except AssertionError:
        print 'Negative cycle exists'


コード例 #2
0
    def distance_to(self, v):
        return self.distances[v]

    def path_to(self, v):
        path = []
        p = v
        while p is not None:
            path.insert(0, p)
            p = self.parentChain[p]

        return path

if __name__ == "__main__":
    import graph_utils

    dag = graph_utils.load_weighted_digraph('../data/tinyEWDAG.txt', True)

    dag_sp = DAGShortestPath(dag)

    source = 5
    dag_sp.shortest_path(source)

    for i in range(dag.V()):
        print "%d to %d (%f): " % (source, i, dag_sp.distance_to(i)), dag_sp.path_to(i)

    dag_sp.longest_path(source)

    for i in range(dag.V()):
        print "%d to %d (%f): " % (source, i, dag_sp.distance_to(i)), dag_sp.path_to(i)
コード例 #3
0
                        self.weights[i][j] = through_k

    def shortest_shortest(self):
        shortest_path = 1e100
        for v in self.weights.values():
            shortest_path = min(min(v), shortest_path)
        return shortest_path

    def has_negative_cycle(self):
        for k in range(self.num_vertices):
            if self.weights[k][k] < 0:
                return True
        return False

if __name__ == "__main__":
    import graph_utils

    G = graph_utils.load_weighted_digraph('../data/floy-warshall-negative_cycle.txt')

    fw = FloydWarshall(G)
    fw.all_shortest_paths()
    assert fw.has_negative_cycle()


    G = graph_utils.load_weighted_digraph('../data/floyd-warshall-1000.txt')

    fw = FloydWarshall(G)
    fw.all_shortest_paths()
    assert not fw.has_negative_cycle()
    print(fw.shortest_shortest())