圖最短路徑之Dijkstra
阿新 • • 發佈:2021-08-29
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));
}
}