图中两个节点之间的最大距离

时间:2020-09-02 01:49:18

标签: graph dijkstra

有没有一种算法可以找到图中两个节点之间的最大距离。该图可能包含周期,也可能不包含周期。

我试图逆转dijkstra的实现,以使其在最长的路径上工作,但不确定我要去哪里。


def rev_djisktra(graph: WeightedGraph, starting_vertex):
    distances = {vertex: -float('infinity') for vertex in graph.neighbors}
    distances[starting_vertex] = 0
    pq = [(0, starting_vertex)]
    while pq:
        neg_distance, current_vertex = heapq.heappop(pq)
        current_distance = -1 * neg_distance
        # Nodes can get added to the priority queue multiple times. We only
        # process a vertex the first time we remove it from the priority queue.
        if current_distance < distances[current_vertex]:
            continue

        for neighbor in graph.neighbors[current_vertex]:
            distance = current_distance + graph.weigths.get((current_vertex, neighbor))
             # Only consider this new path if it's better than any path we've
            # already found.
            if distance > distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(pq, (-distance, neighbor))

    return distances

加权图的实现可能看起来像这样

class WeightedGraph:
    def __init__(self):
        # [4] -> {1,2,}
        self.neighbors = defaultdict(set)
        # (1,2) -> 3
        self.weigths = {}

    def add_vertex(self, vertex):
        self.neighbors[vertex] = set()

    def add_edge(self, src, dest, weight):
        self.neighbors[src].add(dest)
        self.neighbors[dest].add(src)
        self.weigths[(src, dest)] = weight
        self.weigths[(dest, src)] = weight


g = WeightedGraph()

g.add_vertex('a')
g.add_vertex('b')
g.add_vertex('c')
g.add_vertex('d')
g.add_vertex('e')
g.add_vertex('f')

g.add_edge('a', 'b', 7)
g.add_edge('a', 'c', 9)
g.add_edge('a', 'f', 14)
g.add_edge('b', 'c', 10)
g.add_edge('b', 'd', 15)
g.add_edge('c', 'd', 11)
g.add_edge('c', 'f', 2)
g.add_edge('d', 'e', 6)
g.add_edge('e', 'f', 9)

0 个答案:

没有答案