/**
* 最短路径算法:迪杰斯特拉(Dijkstra)算法*
* @author timmy1
*
*/
public class ShortestPath {
int[][] matrix;// 矩阵
int MAX_VALUE = 65535;
int size;
/**
* 迪杰斯特拉算法求最短路径:和普里姆算法思路差不多,默认初始化为第一行的顶点权值数组-》找打最短权值的顶点-》然后再以该顶点去遍历,判断最短的路径
*/
private void dijkstra() {
int[] shortPath = new int[size];
boolean[] isgetPath = new boolean[size];
int minPath;
int minVertex = 0;// 找到的最短权值的顶点
int sum = 0;
// 初始化第一行顶点权值路径
for (int i = 0; i < size; i++) {
shortPath[i] = matrix[0][i];
}
isgetPath[0] = true;
PrintUtil.print("从第0个顶点开始查找");
for (int i = 1; i < size; i++) {
minPath = MAX_VALUE;
// 找到已知权值数组中最小的权值
for (int j = 1; j < size; j++) {
if (!isgetPath[j] && shortPath[j] < minPath) {
minPath = shortPath[j];
minVertex = j;
}
}
sum+= minPath;
PrintUtil.print("找到最短路径顶点:" + minVertex+" 权值为:"+minPath);
isgetPath[minVertex] = true;
for (int j = 1; j < size; j++) {
// 根据找到的最端路径的顶点去遍历添加,最新路径
if (!isgetPath[j] && (minPath + matrix[minVertex][j]) < shortPath[j]) {
shortPath[j] = minPath + matrix[minVertex][j];
}
}
}
PrintUtil.print("---------最短路径为:"+sum);
for (int j = 1; j < size; j++) {
PrintUtil.print("找到V0到顶点V" + j + "的最短路径:"+shortPath[j]);
}
}
private void createGraph(int index) {
size = index;
matrix = new int[index][index];
int[] a0 = { 0, 1, 5, MAX_VALUE, MAX_VALUE, MAX_VALUE, MAX_VALUE, MAX_VALUE, MAX_VALUE };
int[] a1 = { 1, 0, 3, 7, 5, MAX_VALUE, MAX_VALUE, MAX_VALUE, MAX_VALUE };
int[] a2 = { 5, 3, 0, MAX_VALUE, 1, 7, MAX_VALUE, MAX_VALUE, MAX_VALUE };
int[] a3 = { MAX_VALUE, 7, MAX_VALUE, 0, 2, MAX_VALUE, 3, MAX_VALUE, MAX_VALUE };
int[] a4 = { MAX_VALUE, 5, 1, 2, 0, 3, 6, 9, MAX_VALUE };
int[] a5 = { MAX_VALUE, MAX_VALUE, 7, MAX_VALUE, 3, 0, MAX_VALUE, 5, MAX_VALUE };
int[] a6 = { MAX_VALUE, MAX_VALUE, MAX_VALUE, 3, 6, MAX_VALUE, 0, 2, 7 };
int[] a7 = { MAX_VALUE, MAX_VALUE, MAX_VALUE, MAX_VALUE, 9, 5, 2, 0, 4 };
int[] a8 = { MAX_VALUE, MAX_VALUE, MAX_VALUE, MAX_VALUE, MAX_VALUE, MAX_VALUE, 7, 4, 0 };
matrix[0] = a0;
matrix[1] = a1;
matrix[2] = a2;
matrix[3] = a3;
matrix[4] = a4;
matrix[5] = a5;
matrix[6] = a6;
matrix[7] = a7;
matrix[8] = a8;
}
public static void main(String[] args) {
ShortestPath shPath = new ShortestPath();
shPath.createGraph(9);
shPath.dijkstra();
}
}
结果打印:
从第0个顶点开始查找
找到最短路径顶点:1 权值为:1
找到最短路径顶点:2 权值为:4
找到最短路径顶点:4 权值为:5
找到最短路径顶点:3 权值为:7
找到最短路径顶点:5 权值为:8
找到最短路径顶点:6 权值为:10
找到最短路径顶点:7 权值为:12
找到最短路径顶点:8 权值为:16
---------最短路径为:63
找到V0到顶点V1的最短路径:1
找到V0到顶点V2的最短路径:4
找到V0到顶点V3的最短路径:7
找到V0到顶点V4的最短路径:5
找到V0到顶点V5的最短路径:8
找到V0到顶点V6的最短路径:10
找到V0到顶点V7的最短路径:12
找到V0到顶点V8的最短路径:16