迪杰斯特拉,打印经过的最短路径
// 打印路径
public static void printPath(int[] previous, int source, int destination) {
System.out.print("从节点 " + source + " 到节点 " + destination + " 的路径是: ");
System.out.println(Arrays.toString(previous));
//创建当前节点,赋值为目的节点
int current = destination;
// 存储经过的路径
String path = "";
// current !=1 是因为初始化的值为-1,当为-1的时候表示到达了最初起点
while (current != -1) {
// 在这块添加路径
path = current + " -> " + path;
// 将当前从pre路径中获取上一个节点,然后赋值给当前节点
current = previous[current];
}
System.out.println(path);
}