public class Dijk {
public static void dijkstra(int v,int[][] f,int[] d,int[] pre) {
int n = d.length-1;
boolean[] s = new boolean[n+1];
for(int j=1;j<=n;j++) {
d[j] = f[v][j];
s[j] = false;
if(d[j] == Integer.MAX_VALUE)
pre[j] = 0;
else
pre[j] = v;
}
s[v] = true;
d[v] = 0;
int u = v;
int min;
for(int i=1;i<n;i++) {
min = Integer.MAX_VALUE;
for(int j=1;j<=n;j++) {
if((!s[j])&&min > d[j]) {
min = d[j];
u = j;
}
}
s[u] = true;
for(int j=1;j<=n;j++) {
if ((!s[j]) && (f[u][j] < Integer.MAX_VALUE)) {
int newdist = d[u] + f[u][j];
if (newdist < d[j]) {
d[j] = newdist;
pre[j] = u;
}
}
}
}
}
public static void trace(int[] pres, int pre) {
if(pre ==1) {
System.out.print(1);
return;
}
if(pre ==0){
System.out.println("不可达");
return;
}
trace(pres,pres[pre]);
System.out.print(" " + pre);
}
public static void main(String[] args) {
int max = Integer.MAX_VALUE;
//有线图各顶点之间的距离权重,max为不可达
int[][] a = {
{ max, max, max, max, max, max, max},
{ max, 0 , 3 , 4 , max, max, max},
{ max, max, 0 , 1 , 9 , 4 , max},
{ max, max, max, 0 , 5 , 13 , max},
{ max, max, max, max,0 , max, 8 },
{ max, max, max, max, 12 , 0 , 10 },
{ max, max, max, max, max, max, 0 }
};
int n = a.length;
//最短距离
int[] dist = new int[n];
//距离上个顶点
int[] prev = new int[n];
dijkstra(1, a, dist, prev);
System.out.print(" 顶点1到2的最短路径: ");
trace(prev, 2);
System.out.println();
System.out.print(" 顶点1到3的最短路径: ");
trace(prev, 3);
System.out.println();
System.out.print(" 顶点1到4的最短路径: ");
trace(prev, 4);
System.out.println();
System.out.print(" 顶点1到5的最短路径: ");
trace(prev, 5);
System.out.println();
System.out.print(" 顶点1到6的最短路径: ");
trace(prev, 6);
}
}
Dijkstra算法求最短路径
最新推荐文章于 2024-01-15 15:16:22 发布