Longest path in graph

后端 未结 4 1653
一生所求
一生所求 2021-01-24 00:24

Since last 2 days,i\'m trying to find some logic for calculating longest path in graph.I know i can find it easily for DAGs and in general it is polynomial time algorithm.Formal

4条回答
  •  臣服心动
    2021-01-24 01:08

    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 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;
    }
    

    }

提交回复
热议问题