1
希望你做得很好! 我想編寫一個程序,我需要創建一個動態加權圖並獲得從一個頂點到另一個頂點的最短路徑。但在運行程序後,我得到這個異常:JGrapht:添加頂點和邊後的動態圖形錯誤
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);
}
}
非常感謝!這工作 –
快樂,適合你 – Yacino