
image.png
public class Dijkstra {
public static void main(String[] args) {
//初始化节点数据
int[][] data =initMap();
//总节点数
int nodeSize = data[0].length;
//所有便利过的节点
boolean[] done =new boolean[nodeSize];
//0到个节点最短路径长度
int[] shortLine =new int[]{0, 99999, 99999, 99999, 99999, 99999, 99999};
Queue queue =new PriorityQueue<>(Comparator.comparingInt(value -> value.length));
//初始化0节点
queue.add(new Node(0, 0));
while (!queue.isEmpty()) {
Node node = queue.poll();
done[node.id] =true;
for (int index =1; index < nodeSize; index++) {
//说明node.id节点到不了index节点
if (data[node.id][index] ==0) {
continue;
}
//0节点通过node.id到index的长度
int totalLength = node.length + data[node.id][index];
if (!done[index] && shortLine[index] > totalLength ) {
shortLine[index] = totalLength;
queue.add(new Node(index, totalLength));
}
}
}
Arrays.stream(shortLine).forEach(System.out::println);
}
static class Node {
//存储当前节点的id
private int id;
//存储0节点到当前节点的距离
private int length;
Node(int id, int length) {
this.id = id;
this.length = length;
}
}
private static int[][]initMap() {
int[][] map =new int [7][7];
map[0][1]=12;map[0][2]=14;map[0][3]=16;
map[1][0]=12;map[1][3]=7;map[1][4]=10;
map[2][0]=14;map[2][3]=9;
map[3][0]=16;map[3][1]=7;map[3][2]=9;map[3][4]=6;map[3][5]=2;
map[4][1]=10;map[4][3]=6;map[4][5]=5;map[4][6]=3;
map[5][2]=8;map[5][4]=5;map[5][6]=4;map[5][3]=2;
map[6][4]=3;map[6][5]=4;
return map;
}
}
网友评论