2

I'm trying to implement a longest path algorithm in Java with jGraphT, but i get an java.lang.StackOverflowError when i compile. The error message point to the line where i copy the graph and to the line where the method calls itself inside the algorithm. The algorithm description i use is here Liao Wong longest path at page 11.

Where and what have i done wrong?

import org.jgrapht.*;
import org.jgrapht.graph.*;
import java.util.*;

public class LongestPath {
    private DirectedWeightedMultigraph<Vertice, DefaultWeightedEdge> graph;
    private double product;
    private ArrayList<DefaultWeightedEdge> edges;

    public LongestPath(DirectedWeightedMultigraph<Vertice, DefaultWeightedEdge> theGraph) {
        this.graph = theGraph;
        this.product = 1.0;
        this.edges = new ArrayList<DefaultWeightedEdge>();
    }

    public ArrayList<DefaultWeightedEdge> liaoWongLongestPath(Vertice source) {
        DirectedWeightedMultigraph<Vertice, DefaultWeightedEdge> copyGraph =     (DirectedWeightedMultigraph<Vertice, DefaultWeightedEdge>) graph.clone();
        boolean flag;

        for (int j = 1;j <= (copyGraph.edgeSet().size() + 1);j++) {

            edges = this.liaoWongLongestPath(source);

            flag = true;

            for (DefaultWeightedEdge dwe : edges) {

                if (copyGraph.getEdgeWeight(copyGraph.getEdge(source, copyGraph.getEdgeTarget(dwe))) < (copyGraph.getEdgeWeight(copyGraph.getEdge(source, copyGraph.getEdgeSource(dwe))) + copyGraph.getEdge(copyGraph.getEdgeSource(dwe), copyGraph.getEdgeTarget(dwe)).getWeight())) { 
                    //product = (copyGraph.getEdgeWeight(copyGraph.getEdge(source, copyGraph.getEdgeSource(dwe))) * copyGraph.getEdge(copyGraph.getEdgeSource(dwe), copyGraph.getEdgeTarget(dwe)).getWeight());
                    flag = false;
                    boolean status = edges.add(copyGraph.getEdge(source, copyGraph.getEdgeTarget(dwe)));
                }
            }
            if (flag) {
                System.out.println("Product: " + product + ".");
                return edges;
            }
        }

        return edges;
    }
}
Whiteface
  • 21
  • 2

1 Answers1

0

You do a recursive call in your code and you do a copy of the whole graph in each iteration. This is very expensive and in general this will lead to a Stack overflow exception. Try to remove the recursive complexity of this program and/or reuse the graph (you might want to use the MaskSubgraph class).

Please also have a look at this: What is a StackOverflowError?

Community
  • 1
  • 1
Matthias Kricke
  • 4,931
  • 4
  • 29
  • 43