算法推導過程參見【dijkstra算法推導詳解】html
此文爲【dijkstra算法代碼實現】java
http://www.javashuo.com/article/p-oaqkoksp-cv.html算法
package a; import java.util.Arrays; /** * ┏┓ ┏┓+ + * ┏┛┻━━━┛┻┓ + + * ┃ ┃ * ┃ ━ ┃ ++ + + + * ████━████ ┃+ * ┃ ┃ + * ┃ ┻ ┃ * ┃ ┃ + + * ┗━┓ ┏━┛ * ┃ ┃ * ┃ ┃ + + + + * ┃ ┃ Code is far away from bug with the animal protecting * ┃ ┃ + 神獸保佑,代碼無bug * ┃ ┃ * ┃ ┃ + * ┃ ┗━━━┓ + + * ┃ ┣┓ * ┃ ┏┛ * ┗┓┓┏━┳┓┏┛ + + + + * ┃┫┫ ┃┫┫ * ┗┻┛ ┗┻┛+ + + + * * @Author:Halburt * @Date:2019-04-24 下午 5:47 * @Description: */ public class DijkstraDemo { // 表示無窮大 即不可達 public static int NO_AIRPLANE = Integer.MAX_VALUE; // 初始直飛價格表 public int[][] prices ; // 最優起色價格表 public int[] minPrice ; public boolean[] flag ; private int citySize; /** * @param citySize 城市數量 */ public DijkstraDemo(int citySize){ this.citySize = citySize; // prices = new int [citySize][citySize]; flag = new boolean [citySize - 1]; minPrice = new int[citySize - 1 ]; } public static int[][] getPrices(){ int ZH = 0,SH = 1, BJ = 2, GZ = 3,CQ = 4,NJ = 5, HZ = 6,LS = 7; int[][] prices = new int[8][8]; //from Zhuhai prices[ZH][CQ] = 1100; prices[ZH][SH] = 600; prices[ZH][BJ] = 900; prices[ZH][GZ] = 200; //others prices[CQ][NJ] = 400; prices[SH][CQ] = 400; prices[SH][BJ] = 500; prices[SH][NJ] = 200; prices[BJ][SH] = 400; prices[BJ][HZ] = 500 ; prices[BJ][LS] = 1400; prices[GZ][BJ] = 600 ; prices[GZ][LS] = 1500 ; prices[NJ][HZ] = 300 ; prices[HZ][SH] = 200 ; for(int i = 0 ; i < 8 ; i++){ for(int j = 0 ; j < 8 ; j++){ if(prices[i][j] == 0){ prices[i][j] = NO_AIRPLANE; } } } return prices; } public static void main(String[] args) { DijkstraDemo demo = new DijkstraDemo(8); demo.dijkstra(getPrices()); } public void dijkstra(int[][] prices ){ this.prices = prices; // 初始化 // 初始化始發站價格表 for(int i = 1; i < citySize;i++){ minPrice[i-1] = prices[0][i]; } System.out.println("初始化最優表:" + Arrays.toString(minPrice)); dijkstra(); System.out.println("最終最優價格表:" + Arrays.toString(minPrice)); } private void dijkstra(){ int min = Integer.MAX_VALUE; int minIdx = Integer.MAX_VALUE; // 找到最小的價格 for(int idx = 0 ; idx < minPrice.length ; idx ++ ) { if(!flag[idx] && minPrice[idx] < min ){ min = minPrice[idx]; minIdx = idx ; } }//=已經沒有最小的了 if(minIdx == Integer.MAX_VALUE){ return ; } //標記從該城市起色 flag[minIdx] = true; minIdx += 1; System.out.println("起色城市序號"+minIdx +" 價格"+ minPrice[minIdx -1]); //獲取該城市起色時飛往其餘城市的價格表 int cityPrice = minPrice[minIdx -1]; //獲取杭州飛往該城市的價格 int[] minCityPrices = prices[minIdx]; for(int idx = 1 ; idx < citySize ; idx ++ ){ int price = minCityPrices[idx]; // 若是從杭州到達該城市的價格 加上 idx城市起色的價格 低於 從杭州到達idx城市的價格 則更新 if(!flag[idx -1 ] && price != NO_AIRPLANE && (cityPrice+ price) < minPrice[idx - 1]){ // 可達的城市到達的 minPrice[idx - 1] = cityPrice+ price; System.out.println(idx+"更新最優表:" + Arrays.toString(minPrice)); } } dijkstra(); } }