Dijkstra算法,可以从给定一个图和图中的源顶点src,找到从src到给定图中所有顶点的最短路径。但是图不能包含负权重边。时间复杂度O(n^2)。以下代码参考:https://blog.csdn.net/shui2104/article/details/107053966,与原文代码不同的是根据需要增加了最短路径的计算。该博主把算法的原理以及过程都解释非常的详细,具体算法的过程详解请参考https://blog.csdn.net/shui2104/article/details/107053966
package graph.dijkstra;
?
import java.util.Arrays;
?
public class ShortestPathOfDijkstra {
private static final int MAX = 10000;
?
/**
* 接受一个有向图的权重矩阵,和一个起点编号start(从0编号,顶点存在数组中)
*
* @param graph graph
* @param startPointIndex startPointIndex
* @return 返回一个int[] 数组,表示从start到它的最短路径长度
*/
public static int[] dijsktra(int[][] graph, int startPointIndex) {
int length = graph.length;
//标记当前该顶点的最短路径是否已经求出,true表示已经求出
boolean[] visited = new boolean[length];
//start点的最短距离已经求出
for (int i = 0; i < graph.length; i++) {//初始化s集合,只有起始点
if (i == startPointIndex) {
visited[i] = true;
} else {
visited[i] = false;
}
}
?
//存放从start到各个点的最短距离
int[] shortDistance = new int[length];
?
for (int i = 0; i < graph.length; i++) {//初始化,起始点到其他点的距离。
shortDistance[i] = graph[startPointIndex][i];
}
?
//start到他本身的距离最短为0
shortDistance[startPointIndex] = 0;
?
?
//存放从start点到各点的最短路径的字符串表示
String[] path = new String[length];
for (int i = 0; i < length; i++) {
path[i] = startPointIndex + "->" + i;
}
?
for (int count = 1; count < length; count++) {
int k = -1;
int dmin = MAX;
for (int i = 0; i < length; i++) {
if (!visited[i] && shortDistance[i] < dmin) {
dmin = shortDistance[i];
k = i;
}
}
//选出一个距离start最近的未标记的顶点 将新选出的顶点标记为以求出最短路径,且到start的最短路径为dmin。
shortDistance[k] = dmin;
visited[k] = true;
//以k为中间点,修正从start到未访问各点的距离
for (int i = 0; i < length; i++) {
if (!visited[i] && shortDistance[k] + graph[k][i] < shortDistance[i]) {
shortDistance[i] = shortDistance[k] + graph[k][i];
path[i] = path[k] + "->" + i;
}
}
}
for (int i = 0; i < length; i++) {
System.out.println("从" + startPointIndex + "出发到" + i + "的最短路径为:" + path[i] + "=" + shortDistance[i]);
}
return shortDistance;
}
?
public static void main(String[] args) {
int[][] graph = {
{0, 4, 6, 6, MAX, MAX, MAX},
{MAX, 0, 1, MAX, 7, MAX, MAX},
{MAX, MAX, 0, MAX, 6, 4, MAX},
{MAX, MAX, 2, 0, MAX, 5, MAX},
{MAX, MAX, MAX, MAX, 0, MAX, 6},
{MAX, MAX, MAX, MAX, 1, 0, 8},
{MAX, MAX, MAX, MAX, MAX, MAX, MAX}};
int start = 0;
int[] dijsktra = dijsktra(graph, start);
System.out.println(Arrays.toString(dijsktra));
}
}
图最短路径之Dijkstra