算法概要:从没有访问的点里,找到距离起点最近的点,然后更新该点到其相邻且未访问点的距离
1.找出距离最小的点s1 这块我其实有个疑问,如果be这个顶点和别的点都不连接,那么这块计算不下去了?
2.根据s1到它连接的每一个e1,如果 (开始节点->s1)+(s1->e1)<(开始节点->e1) 那么开始节点->e1需要更新一下
package info.frady.algo;
/**
meng3.wei 2020.04.25
//参考 https://www.jianshu.com/p/ff6db00ad866
从0出发到0的最短距离为:0
0-->0
从0出发到1的最短距离为:3
0-->3-->1
从0出发到2的最短距离为:3
0-->3-->2
从0出发到3的最短距离为:2
0-->3
从0出发到4的最短距离为:6
0-->3-->2-->4
*/
public class 迪杰斯特拉 {
public static final int M = 1000000; // 代表正无穷
public static int n;//顶点的个数
public static int[] shortPathLen ; // 保存start到其他各点的最短路径
public static boolean [] visited;
public static int[] pid;
public static void main(String[] args) {
// 二维数组每一行分别是 A、B、C、D、E 各点到其余点的距离,
// A -> A 距离为0, 常量M 为正无穷
int[][] weight1 = {
{0,4,M,2,M},
{4,0,4,1,M},
{M,4,0,1,3},
{2,1,1,0,7},
{M,M,3,7,0}
};
n=weight1.length;
pid=new int[n];
visited=new boolean[n];
shortPathLen=new int[n];
int be=0;
proceeDS(weight1,be);
for (int i = 0; i < n; i++) {
System.out.println("从" + 0 + "出发到" + i + "的最短距离为:" + shortPathLen[i]);
int p=pid[i];
StringBuffer sb=new StringBuffer();
sb.append(i);
while(p!=be){
sb.append(">--"+p);
p=pid[p];
}
sb.append(">--"+be);
System.out.println(sb.reverse());
}
}
public static void proceeDS(int[][] weight1,int be){//be代表起点
pid[be]=be;
visited[be]=true;
shortPathLen[be]=0;
for (int i = 1; i < n; i++) {
int minLen=Integer.MAX_VALUE;
int s1=0;
for (int end = 0; end <n ; end++) {//1.找出距离最小的点s1 这块我其实有个疑问,如果be这个顶点和别的点都不连接,那么这块计算不下去了?
if(!visited[end] && weight1[be][end]<minLen ){
s1=end;
minLen=weight1[be][end];
}
}
shortPathLen[s1]=minLen;
visited[s1]=true;
for (int e1 = 0; e1<n ; e1++) {//2.根据s1到它连接的每一个e1,如果 (开始节点->s1)+(s1->e1)<(开始节点->e1) 那么开始节点->e1需要更新一下
if( !visited[e1] && (weight1[be][s1]+ weight1[s1][e1] <weight1[be][e1]) ){
weight1[be][e1]=weight1[be][s1]+ weight1[s1][e1];
pid[e1]=s1;
}
}
}
}
}