在使用两个案例测试代码时,我发现没有问题,这两个案例是从静态数据和控制台输入构建的。
以下是我的案例处理方法:
private static final Graph.Edge[] buildData()
{
Graph.Edge[] GRAPH = {
new Graph.Edge("A", "B", 5),
new Graph.Edge("C", "D", 7),
new Graph.Edge("E", "F", 3),
new Graph.Edge("G", "H", 2),
new Graph.Edge("B", "C", 1),
new Graph.Edge("D", "E", 9),
new Graph.Edge("A", "H", 4),
new Graph.Edge("G", "B", 6)
};
return GRAPH;
}
和两种方法。
public static void main_build(String[] args) {
String START = "A";
String END = "G";
Graph.Edge[] GRAPH = buildData();
Graph g = new Graph(GRAPH);
g.dijkstra(START);
// print the shortest path using Dijkstra algorithm
g.printPath(END);
//g.printAllPaths();
}
public static void main_input(String[] args) {
Scanner sc = new Scanner(System.in);
//int n = sc.nextInt();
//
Graph.Edge[] GRAPH = {
new Graph.Edge(sc.next(), sc.next(), sc.nextInt()),
new Graph.Edge(sc.next(), sc.next(), sc.nextInt()),
new Graph.Edge(sc.next(), sc.next(), sc.nextInt()),
new Graph.Edge(sc.next(), sc.next(), sc.nextInt()),
new Graph.Edge(sc.next(), sc.next(), sc.nextInt()),
new Graph.Edge(sc.next(), sc.next(), sc.nextInt()),
new Graph.Edge(sc.next(), sc.next(), sc.nextInt()),
new Graph.Edge(sc.next(), sc.next(), sc.nextInt())
};
String START = sc.next();
String END = sc.next();
Graph g = new Graph(GRAPH);
g.dijkstra(START);
// print the shortest path using Dijkstra algorithm
g.printPath(END);
// g.printAllPaths();
sc.close();
sc = null;
}
第二种方法的键输入,main\u输入必须是,
A B 5 C D 7 E F 3 G H 2 B C 1 D E 9 A H 4 G B 6 A G
关于for循环语句,它的方式与我前面描述的方法相同。
这里有一个for循环方法,
for循环语句如下所示;
public static void main_forloop(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Graph.Edge[] GRAPH = new Graph.Edge[n];
for(int i = 0; i < n; i++) {
GRAPH[i] =
new Graph.Edge(sc.next(),sc.next(),sc.nextInt());
}
String START = sc.next();
String END = sc.next();
Graph g = new Graph(GRAPH);
g.dijkstra(START);
// print the shortest path using Dijkstra algorithm
g.printPath(END);
// g.printAllPaths();
sc.close();
sc = null;
}
控制台输入为:
8 A B 5 C D 7 E F 3 G H 2 B C 1 D E 9 A H 4 G B 6 A G
您可以在eclipse环境中将out和以下控制台输出图像与您的进行比较。
关于dijkstra算法的文章很多。
我认为这不是程序问题,而是测试数据。
我发现这个网站有测试数据文件。
Shortest Paths
您可以使用来自站点的数据来测试代码-您需要使用java中的文件流类从文件中构建数据。
我希望这能帮助你。