基本原理:
迪傑斯特拉算法是一種貪心算法。
首先建立一個集合,初始化只有一個頂點。每次將當前集合的所有頂點(初始只有一個頂點)看成一個整體,找到集合外與集合距離最近的頂點,將其加入集合並檢查是否修改路徑距離(比較在集合內源點到達目標點中各個路徑的距離,取最小值),以此類推,直到將所有點都加入集合中。得到的就是源點到達各頂點最短距離。時間復雜度為 O(n^2)。
變量解釋:
1、采用圖的鄰接矩陣存儲結構;
2、輔助數組visited[n] :表示當前頂點的最短路徑是否求出,1表示求出;
3、輔助數組path[n] :記錄路徑,字符串類型;
4、返回結果shortPath[n]
算法代碼:
1 public class Dijkstra { 2 public static final int M = 10000; // 代表正無窮 3 4 //案例演示 5 public static void main(String[] args) { 6 // 二維數組每一行分別是 A、B、C、D、E 各點到其余點的距離, 7 // A -> A 距離為0, 常量M 為正無窮 8 int[][] weight1 = { 9 {0,4,M,2,M}, 10 {4,0,4,1,M}, 11 {M,4,0,1,3}, 12 {2,1,1,0,7}, 13 {M,M,3,7,0} 14 }; 15 16 int start = 0; 17 18 int[] shortPath = dijkstra(weight1, start); 19 20 for (int i = 0; i < shortPath.length; i++) 21 System.out.println("從" + start + "出發到" + i + "的最短距離為:" + shortPath[i]); 22 } 23 24 public static int[] dijkstra(int[][] weight, int start) { 25 // 接受一個有向圖的權重矩陣,和一個起點編號start(從0編號,頂點存在數組中) 26 // 返回一個int[] 數組,表示從start到它的最短路徑長度 27 int n = weight.length; // 頂點個數 28 int[] shortPath = new int[n]; // 保存start到其他各點的最短路徑 29 String[] path = new String[n]; // 保存start到其他各點最短路徑的字符串表示 30 for (int i = 0; i < n; i++) 31 path[i] = new String(start + "-->" + i); 32 int[] visited = new int[n]; // 標記當前該頂點的最短路徑是否已經求出,1表示已求出 33 34 // 初始化,第一個頂點已經求出 35 shortPath[start] = 0; 36 visited[start] = 1; 37 38 for (int count = 1; count < n; count++) { // 要加入n-1個頂點 39 int k = -1; // 選出一個距離初始頂點start最近的未標記頂點 40 int dmin = Integer.MAX_VALUE; 41 for (int i = 0; i < n; i++) { 42 if (visited[i] == 0 && weight[start][i] < dmin) { 43 dmin = weight[start][i]; 44 k = i; 45 } 46 } 47 48 // 將新選出的頂點標記為已求出最短路徑,且到start的最短路徑就是dmin 49 shortPath[k] = dmin; 50 visited[k] = 1; 51 52 // 以k為中間點,修正從start到未訪問各點的距離 53 for (int i = 0; i < n; i++) { 54 //如果 '起始點到當前點距離' + '當前點到某點距離' < '起始點到某點距離', 則更新 55 if (visited[i] == 0 && weight[start][k] + weight[k][i] < weight[start][i]) { 56 weight[start][i] = weight[start][k] + weight[k][i]; 57 path[i] = path[k] + "-->" + i; 58 } 59 } 60 } 61 for (int i = 0; i < n; i++) { 62 63 System.out.println("從" + start + "出發到" + i + "的最短路徑為:" + path[i]); 64 } 65 System.out.println("====================================="); 66 return shortPath; 67 } 68 69 }