我正在尝试使用 jGraphT 在 Java 中实现最长路径算法,但是在编译时出现 java.lang.StackOverflowError。错误消息指向我复制图形的行以及该方法在算法内部调用自身的行。我使用的算法描述是Liao Wong 最长路径,第 11 页。
我在哪里做错了什么?
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;
}
}