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