Finding Longest Paths in Directed Graphs with Bellman-Ford Algorithm

  • Share this:

Code introduction


This code defines a function that uses the Bellman-Ford algorithm to find the longest path from a starting vertex to all other vertices in a directed graph. If the graph contains a negative-weight cycle, an exception is raised.


Technology Stack : The code uses the Graph-tool library.

Code Type : The type of code

Code Difficulty :


                
                    
def find_longest_path(graph, start_vertex):
    # Find the longest path in a directed graph using the Bellman-Ford algorithm
    n_vertices = graph.num_vertices()
    distances = [float('inf')] * n_vertices
    predecessors = [-1] * n_vertices
    distances[start_vertex] = 0

    # Relax edges repeatedly
    for _ in range(n_vertices - 1):
        for u in graph.vertices():
            for v, weight in graph.out_edges(u):
                if distances[u] + weight < distances[v]:
                    distances[v] = distances[u] + weight
                    predecessors[v] = u

    # Check for negative-weight cycles
    for u in graph.vertices():
        for v, weight in graph.out_edges(u):
            if distances[u] + weight < distances[v]:
                raise ValueError("Graph contains a negative-weight cycle")

    # Reconstruct the longest path
    def reconstruct_path(v):
        if v == start_vertex:
            return [v]
        else:
            return reconstruct_path(predecessors[v]) + [v]

    longest_path = reconstruct_path(max(range(n_vertices), key=lambda i: distances[i]))
    return longest_path