我正在尝试使用jGraphT在Java中实现最长路径算法,但是在编译时我得到了一个java.lang.StackOverflowError。错误消息指向我复制图形的行以及方法在算法中调用自身的行。我使用的算法描述在第11页Liao Wong longest path。
我做错了哪里和哪里?
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;
}
}
答案 0 :(得分:0)
您在代码中执行递归调用,并在每次迭代中复制整个图形。这非常昂贵,通常这会导致堆栈溢出异常。尝试删除此程序的递归复杂性和/或重用图形(您可能希望使用MaskSubgraph类)。