Longest path in graph

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-02 06:50:55

Calculating longest path cannot be done in polynomial time as far as I know. Following java implementation of the longest path algorithm finds the longest path of a positive weighted graph for a given source but it takes exponential time in its worst case.

public class LongestPath {
static int times;
public double initLongestPath(ArrayList<Vertex> V,Vertex source){
    for(Vertex u:V){
        u.setVisited(false);
    }
    return getLongestPath(source);
}
public double getLongestPath(Vertex v){
    ++times;
    System.out.println(times);
    double w,dist,max=0;
    v.setVisited(true);
    for(Edge e:v.getOutGoingEdges()){
        if(!e.getToNode().isVisited()){
            dist=e.getWeight()+getLongestPath(e.getToNode());
            if(dist>max)
                max=dist;
        }
    }

    v.setVisited(false);    
    return max;
}

}

Dijkstra's can't be used on graphs with negative weights - Wiki article on Dijkstra's

Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959,1 is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs ...

So you can't negate all edge weights and use Dijkstra's, what you can do is negate all edge weights and use Bellman-Ford algorithm - Wiki article on Bellman-Ford

The Bellman–Ford algorithm is an algorithm that computes shortest paths from a single source vertex to all of the other vertices in a weighted digraph.1 It is slower than Dijkstra's algorithm for the same problem, but more versatile, as it is capable of handling graphs in which some of the edge weights are negative numbers

EDIT: The shortest path (with the most negative value) is then the longest path in your original graph.

NOTE: if you have positive cycles in your graph, you will not find a solution since the longest path doesn't exist in such a graph.

You could always just use a breadth first search (BFS) and, whenever you are adding an edge to the graph you have it's cost as the additive inverse (multiply it be -1). This way you are finding the 'shortest path' by using the longest edges. Because you're doing a scalar transform, you're not losing the ability to add within the group (which you do lose if you use the multiplicative inverse).

Invert the weights of the paths and run a shortest path algorithm. The lowest number you get (most negative) is the longest path.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!