希望你做得好! 我正在尝试编写一个程序,我需要创建一个动态加权图,并获得从一个顶点到另一个顶点的最短路径。但在运行程序后,我得到了这个例外:
run:
TEST1
TEST Vertex Add
Exception in thread "main" java.lang.IllegalArgumentException: no such vertex in graph: 1
at org.jgrapht.graph.AbstractGraph.assertVertexExist(AbstractGraph.java:132)
at org.jgrapht.graph.AbstractBaseGraph.addEdge(AbstractBaseGraph.java:141)
at dijkstra.Dijkstra.main(Dijkstra.java:26)
C:\Users\Lucas\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
以下是代码:
import org.jgrapht.*;
import org.jgrapht.alg.*;
import org.jgrapht.graph.*;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
public class Dijkstra {
public static void main(String args[]) {
SimpleWeightedGraph<String, DefaultWeightedEdge> graph = new SimpleWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
int i = generateNumberByRange(1,5);
System.out.println("TEST1");
for(int j=0; j<i; j++){
graph.addVertex(String.valueOf(j));
System.out.println("TEST Vertex Add");
}
for(int j=0;j<i;j++){
DefaultWeightedEdge e1 = graph.addEdge(String.valueOf(j),String.valueOf(j+1));
graph.setEdgeWeight(e1, generateNumberByRange(10,20));
System.out.println(graph.getEdgeWeight(e1));
}
System.out.println("TEST2");
graph.addVertex(String.valueOf(i));
DefaultWeightedEdge e = graph.addEdge("0","1");
graph.setEdgeWeight(e, generateNumberByRange(10,20));
System.out.println("TEST3");
System.out.println("Shortest path from START to END:");
//List shortest_path = DijkstraShortestPath.findPathBetween(graph,"0",String.valueOf(i));
List shortest_path;
//shortest_path = DijkstraShortestPath.findPathBetween(graph, "0","2");
//System.out.println(shortest_path);
}
public static int generateNumberByRange(int START, int END){
return ThreadLocalRandom.current().nextInt(START, END + 1);
}
}
答案 0 :(得分:0)
实际上你需要修改这个循环:
for(int j=0;j<i;j++){
DefaultWeightedEdge e1 = graph.addEdge(String.valueOf(j),String.valueOf(j+1));
graph.setEdgeWeight(e1, generateNumberByRange(10,20));
System.out.println(graph.getEdgeWeight(e1));
}
到
for(int j=0;j<i-1;j++){
DefaultWeightedEdge e1 = graph.addEdge(String.valueOf(j),String.valueOf(j+1));
graph.setEdgeWeight(e1, generateNumberByRange(10,20));
System.out.println(graph.getEdgeWeight(e1));
}
因为在循环结束时你试图得到那个不存在这个索引i + 1`的顶点。
希望这个帮助