public class Dijstra {
private static final int MAXVEX = 9;//顶点数
private static final int MAXWEIGHT = 65535;
private int[] shortTablePath = new int[MAXVEX]; //记录v0到某顶点的最短路径和
//获取一个图的最短路径
public void shortestDijstra(Graph graph){
int min;
int k = 0;//记录下标
boolean[] isgetPath = new boolean[MAXVEX]; //是否拿到这个顶点的最短路径
for(int v = 0;v < graph.getVertexSize();v++){
shortTablePath[v] = graph.getMatrix()[0][v]; //获取v0这一行的权值数组
}
shortTablePath[0] = 0;
isgetPath[0] = true;
for(int i = 1;i < graph.getVertexSize();i++){
min = MAXWEIGHT;
for(int j = 0;j < graph.getVertexSize();j++){
if(!isgetPath[j] && shortTablePath[j] < min){ //获取有交点的顶点的下标
k = j;
min = shortTablePath[j];
}
}
isgetPath[k] = true;
for(int z = 0;z < graph.getVertexSize();z++){
if(!isgetPath[z] && (min + graph.getMatrix()[k][z] < shortTablePath[z])){
shortTablePath[z] = min + graph.getMatrix()[k][z];
}
}
}
for(int i = 0;i < graph.getVertexSize();i++){
System.out.println("v0到v" + i + "的最短路径为:" + shortTablePath[i]);
}
}
public static void main(String[] args){
int[] a0 = new int[]{0,1,5,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT};
int[] a1 = new int[]{1,0,3,7,5,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT};
int[] a2 = new int[]{5,3,0,MAXWEIGHT,1,7,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT};
int[] a3 = new int[]{MAXWEIGHT,7,MAXWEIGHT,0,2,MAXWEIGHT,3,MAXWEIGHT,MAXWEIGHT};
int[] a4 = new int[]{MAXWEIGHT,5,1,2,0,3,6,9,MAXWEIGHT};
int[] a5 = new int[]{MAXWEIGHT,MAXWEIGHT,7,MAXWEIGHT,3,0,MAXWEIGHT,5,MAXWEIGHT};
int[] a6 = new int[]{MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,3,6,MAXWEIGHT,0,2,7};
int[] a7 = new int[]{MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,9,5,2,0,4};
int[] a8 = new int[]{MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,7,4,0};
int[][] arr = new int[9][9];
arr[0] = a0;
arr[1] = a1;
arr[2] = a2;
arr[3] = a3;
arr[4] = a4;
arr[5] = a5;
arr[6] = a6;
arr[7] = a7;
arr[8] = a8;
Graph graph = new Graph(9);
graph.setMatrix(arr);
Dijstra d = new Dijstra();
d.shortestDijstra(graph);
}
}