コード例 #1
0
            adjacent_vertex = edge.get_end_vertex()
            if new_distance < distances[adjacent_vertex]:
                distances[adjacent_vertex] = new_distance

    return distances


if __name__ == "__main__":
    graph = Graph()

    graph.add_vertex("a")
    graph.add_vertex("b")
    graph.add_vertex("c")
    graph.add_vertex("d")
    graph.add_vertex("e")
    graph.add_vertex("f")

    graph.add_edge("a", "b", 2)
    graph.add_edge("a", "c", 4)
    graph.add_edge("b", "c", 1)
    graph.add_edge("c", "d", 5)
    graph.add_edge("c", "e", 3)
    graph.add_edge("d", "e", 1)
    graph.add_edge("e", "f", 8)

    display_graph(graph, "Input graph for Dijkstra's algorithm")

    shortest_distances_to_vertices = dijkstra(graph, graph.get_vertex("a"))
    for vertex, distance in shortest_distances_to_vertices.items():
        print("Vertex {0}, Distance {1}".format(vertex.get_label(), distance))
コード例 #2
0
        queue.extend(adjacent_vertices)

    return result


if __name__ == "__main__":
    graph = Graph()

    graph.add_vertex("Jhon")
    graph.add_vertex("Sophia")
    graph.add_vertex("Emma")
    graph.add_vertex("Mark")
    graph.add_vertex("Alice")
    graph.add_vertex("Jeff")
    graph.add_vertex("George")

    graph.add_edge("Jhon", "Sophia")
    graph.add_edge("Jhon", "Emma")
    graph.add_edge("Jhon", "Mark")
    graph.add_edge("Sophia", "Emma")
    graph.add_edge("Sophia", "Alice")
    graph.add_edge("Emma", "Sophia")
    graph.add_edge("Emma", "Jeff")
    graph.add_edge("Jeff", "George")

    display_graph(graph, "Input graph for Breadth-First Search")

    vertices = bfs(graph.get_vertex("Jhon"))
    for vertex in vertices:
        print(vertex)
コード例 #3
0
    graph.add_vertex("a")
    graph.add_vertex("b")
    graph.add_vertex("c")
    graph.add_vertex("d")
    graph.add_vertex("e")
    graph.add_vertex("f")

    graph.add_edge("a", "b")
    graph.add_edge("a", "c")
    graph.add_edge("a", "d")
    graph.add_edge("b", "c")
    graph.add_edge("b", "f")
    graph.add_edge("c", "d")
    graph.add_edge("d", "e")
    graph.add_edge("e", "f")

    start_vertex = graph.get_vertex("a")
    end_vertex = graph.get_vertex("f")
    shortest_path = bfs_shortest_path(start_vertex, end_vertex)

    display_graph(
        graph, "Input graph for BFS shortest path from {0} to {1}".format(
            start_vertex.get_label(), end_vertex.get_label()))

    if shortest_path:
        for vertex in shortest_path:
            print(vertex)
    else:
        print("There no path between {0} & {1}".format(
            start_vertex.get_label(), end_vertex.get_label()))