示例#1
0
def test_weighted_graph():
    g = WeightedGraph()

    g.insert_edge("a", {(9, "b"), (6, "c"), (1, "d")})

    assert g.get_neighbors("a") == {(9, "b"), (6, "c"), (1, "d")}
    assert g.get_neighbors("b") == {(9, "a")}
    assert g.get_neighbors("c") == {(6, "a")}
    assert g.get_neighbors("d") == {(1, "a")}

    assert g.get_weight("a", "b") == 9
    assert g.get_weight("a", "c") == 6
    assert g.get_weight("a", "d") == 1
示例#2
0
def dijkstra(g: WeightedGraph, s: list):
    dist = {}
    pred = {}
    Q = PriorityQueue()

    def relax(u, v):
        if dist[v] > dist[u] + g.get_weight(u, v):
            dist[v] = dist[u] + g.get_weight(u, v)
            pred[v] = u

    while not Q.empty():
        u = Q.get()
        s.append(u)
        for v in g.get_neighbors(u):
            relax(u, v)