Is there an algorithm to find max distance between two nodes in a graph. The graph may or may not contain cycles.
I was trying to reverse dijkstra's implementation to make it work for longest path, but wasn't sure where I was going wrong.
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
The implementation of weighted graph may look something like this
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)