步驟 | 已用點 | 路徑(A->B:權值) | 最短路徑 | 未用點B(遍歷點) | |
1 | 設置矩陣weight,記錄各點間距離(M爲不可到達),設置起始點start,weight[start][i]記錄start到各點的最短距離,shortpath[i]記錄最短路徑,shortpath[start]默認爲0 | 0->0:0 | 0,1,2,3,4 | ||
2 | 讓start=0,0做爲原點,標爲已用,用bool[0]=1表示,比較0到其餘未用點的距離,選取其中權值最小的路徑做爲一條最短路徑(權值最小,不可能有經過其餘點到達該點權值更小的路徑),獲得最短路徑頂點爲3 | 0 | 0->1:13spa 0->2:Mcode 0->3:6blog 0->4:11table |
0->3:6 | 1,2,3,4 |
3 | 獲取經過3到其餘各點的距離,與原weight[start][i]中值比較,使weight[start][i]中均爲start到各點的最短距離,再次比較weight[start][i]中除到0,3點的最小值,得到第三條最短路徑,路徑頂點爲4 | 0,3 | 0->3->1:M(0->1:13)class 0->3->2:23(0->2:M)遍歷 0->3->4:10(0->4:11)im |
0->3->4:10 | 1,2,4 |
4 | 重複步驟3 | 0,3,4 | 0->3->4->1:19(0->1:13)static 0->3->4->2:13(0->3-2:23)img |
0->1:13tab (此處到1,2距離相等,應均爲最短路徑,但爲了代碼方便,選其中一條路徑) |
1,2 |
5 | 重複步驟3 | 0,1,3,4 | 0->1->2:16(0->3->4->2:13) | 0->3->4->2:13 | 2 |
6 | 得到全部最短路徑,可輸出(遍歷完全部點) | 0,1,2,3,4 |
對應圖:
對應代碼:
1 static int M=10000; //不可到達,不可設置爲int類型最大值,不然下面相加時會出錯 2 public static void main(String[] args){ 3 //設置一個圖 4 int[][] weigth={ 5 {0,13,M,6,11},//V0到V0,V1,V2,V3,V4 6 {13,0,3,M,9},//V1到V0,V1,V2,V3,V4 7 {M,3,0,17,3}, 8 {6,M,17,0,4}, 9 {11,9,3,4,0} 10 }; 11 //起始點start 12 int start=0; 13 14 //最短路徑: 15 dijkstra(weigth,start); 16 } 17 private static void dijkstra(int[][] weigth, int start) { 18 int len=weigth.length;//頂點數 19 int[] distance=new int[len];//從start點到其餘點的最短距離 20 String[] shortpath =new String[len];//從start到其餘頂點的最短路徑 21 22 int[] bool=new int[len];//標記是否已收納最短路徑 23 bool[start]=1; 24 int k=-1; 25 distance[start]=0; 26 for(int i=0;i<len;i++){ 27 shortpath[i]=start+"->"+i; 28 } 29 30 for(int count=1;count<len;count++){ 31 int minpath=Integer.MAX_VALUE; 32 for(int j=0;j<len;j++){ 33 if(bool[j] !=1 && weigth[start][j]<minpath){ 34 k=j; 35 minpath=weigth[start][j]; 36 } 37 }//求start到其他各點中權值最小的點 38 bool[k]=1;//標記已使用點{0,k} 39 distance[k]=minpath;//得到點0到點k的最小距離 40 for(int i=0;i<len;i++){ 41 if(bool[i]!=1 && minpath+weigth[k][i]<weigth[start][i]){ 42 shortpath[i]=shortpath[k]+"->"+i; 43 weigth[start][i]=minpath+weigth[k][i]; 44 } 45 }//求start->k->其他各點的距離,若小於start->其他各點距離,將weigth[start][i]設爲那個更小的距離,shortpath記錄經歷的路徑 46 47 } 48 49 //顯示輸出 50 for(int i=0;i<len;i++){ 51 System.out.println("從"+start+"到"+i+"的最短路徑爲:"+shortpath[i]+";最短距離爲:"+distance[i]); 52 } 53 54 }
運算結果:
從0到0的最短路徑爲:0->0;最短距離爲:0 從0到1的最短路徑爲:0->1;最短距離爲:13 從0到2的最短路徑爲:0->3->4->2;最短距離爲:13 從0到3的最短路徑爲:0->3;最短距離爲:6 從0到4的最短路徑爲:0->3->4;最短距離爲:10