案例:
五一快到了,小张准备去旅游了!
查了查到各地的机票
4)用一个数组flag标记城市是否已经转机过
// 表示无穷大 即不可达 public static int NO_AIRPLANE = Integer.MAX_VALUE; // 初始直飞价格表 public int[][] prices ; // 最优转机价格表 public int[] minPrice ; public boolean[] flag ; private int citySize;
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; }
// 初始化始发站价格表 for(int i = 1; i算法实现
private void dijkstra(){ int min = Integer.MAX_VALUE; int minIdx = Integer.MAX_VALUE; // 找到最小的价格 for(int idx = 0 ; idx运行结果
跟上述推到过程一致,希望本文能对你有所帮助。
附件-源码:
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感谢原作者Halburt,原文地址:https://www.cnblogs.com/Halburt/p/10767389.html
以上就是怎么用dijkstra算法找到五一最省旅游路线的详细内容,更多请关注其它相关文章!