


Tomorrow is May Day. Are you ready for your travel guide? Today, the editor will take you through an article about using the dijkstra algorithm to help you easily find travel routes, which is affordable and worry-free. Come and take a look!
Case:
May Day is coming soon, and Xiao Zhang is ready to travel!
Checked the air tickets from various places
Because his salary was deducted severely this year, Xiao Zhang did not have much money and had to be careful with his budget. He wants to find out the lowest cost of going to various cities.
[Well, there’s no need to consider the cost of coming back. Xiao Zhang was going to tell the police uncle that he had been trafficked and he would be sent back for free. 】
If he wants to fly from Zhuhai to Lhasa, how much is the minimum ticket cost? Let’s talk about the algorithm we are going to talk about today.
Dijkstra algorithm
Dijkstra algorithm is a typical single-source shortest path algorithm, used to calculate the shortest path from one node to all other nodes. path. The main feature is that it expands outward layer by layer from the starting point until it reaches the end point. The time complexity of Dijkstra's algorithm is O(N^2).
Extension
Dijkstra was born on May 11, 1930, in an intellectual family in Rotterdam, the Netherlands. She was the third among four brothers and sisters. His father was a chemist and inventor who served as president of the Dutch Chemical Society. His mother is a mathematician. He successfully designed and implemented an efficient algorithm to find the shortest path between two locations with obstacles. This algorithm was named "Dijkstra's algorithm" and solved a very critical problem in robotics. The problem, namely the motion path planning problem, is still widely used today.
Related tutorials: Data Structure Adventure Picture Chapter
Algorithm Derivation
Make a table to record Zhuhai The minimum air ticket cost to each city
We started looking for cities that are directly connected from Zhuhai
The cities that are directly connected to Zhuhai include Shanghai, Beijing, Guangzhou, and Chongqing, then The air ticket prices from Zhuhai to other cities are as follows (if there is no direct connection, we mark infinity):
It can be seen that among these four cities, Guangzhou has the lowest price, so let’s transfer from Guangzhou
The cheapest way to transfer from Guangzhou
The cities that can be directly connected to Guangzhou are Beijing and Lhasa. Then the ticket prices for connecting flights from Zhuhai to other cities from Guangzhou are as follows: (It is impossible to know if you can transfer from Guangzhou)
Comparison found that it is 200 yuan from Zhuhai to Guangzhou and 600 yuan from Guangzhou to Beijing, which is only 800 yuan (it may be a loss of time, but who cares, Xiao Zhang is poor and only has time)
Transferring from Guangzhou, it’s 1700 to Lhasa, so it’s definitely not better than arriving there.
So we have the cheapest price list.
In addition to Guangzhou, let’s find the cheapest city to transfer from Shanghai - Shanghai
Chongqing and Nanjing are the cities directly connected to Shanghai, then Zhuhai can transfer to other cities from Shanghai The air ticket prices in the cities are as follows:
Comparing the original prices, we found that it is cheaper to transfer from Shanghai to Chongqing and Nanjing
Except for Guangzhou and Shanghai, then Let’s then look for the cheapest city for connecting flights - Beijing
Beijing direct to Shanghai (Shanghai has been marked, it must be the cheapest price, in fact, there is no meaning to compare), Hangzhou and Lhasa, the price As follows:
The price to Lhasa is the lowest price to Beijing 800 Beijing-> The sum of the prices of 1400 in Lhasa (2200) is higher than 1700, and 800 to Hangzhou 500 = 1300, then The lowest price list is as follows
In addition to Guangzhou, Shanghai, and Beijing, let’s find the cheapest city for connecting flights - Nanjing
Nanjing can only go directly to Hangzhou,
The price from Nanjing to Hangzhou It’s 1100, which is a good deal
In addition to Guangzhou, Shanghai, Beijing, and Nanjing, let’s find the cheapest city for connecting flights - Chongqing
The only direct connection from Chongqing is Nanjing , and it costs 1000 400 = 1400 yuan to go to Nanjing, which is definitely not cost-effective compared to the original 800 yuan to Nanjing.
Except for Guangzhou, Shanghai, Beijing, Nanjing, and Chongqing, then from us Then I looked for the city with the cheapest transfer - Hangzhou
Hangzhou can only go to Shanghai, and the price is higher than Shanghai
Finally I found Lhasa
Then the cheapest air ticket to Lhasa is 1,700 yuan.
Code implementation
Variable preparation
1) Use 0,1,2,...,7 to represent Zhuhai, Shanghai, Beijing, Guangzhou, Chongqing, Nanjing, respectively. Hangzhou, Lhasa.
2) Use a two-dimensional array prices [8][8] to represent flight prices: prices[i][j] = direct flight price from i to j (if there is no flight, it is recorded as ∞)
3) Use an array minPrice to record the minimum air ticket cost from Zhuhai to various cities:
4) Use an array flag to mark whether the city has been transferred
// 表示无穷大 即不可达 public static int NO_AIRPLANE = Integer.MAX_VALUE; // 初始直飞价格表 public int[][] prices ; // 最优转机价格表 public int[] minPrice ; public boolean[] flag ; private int citySize;
Data preparation
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; }
Initialize the direct flight to Hangzhou The price
// 初始化始发站价格表 for(int i = 1; i < citySize;i++){ minPrice[i-1] = prices[0][i]; }
Algorithm implementation
private void dijkstra(){ int min = Integer.MAX_VALUE; int minIdx = Integer.MAX_VALUE; // 找到最小的价格 for(int idx = 0 ; idxThe running result
is consistent with the above push process. I hope this article can be helpful to you.Attachment-Source code:
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(); } }Thanks to the original author Halburt, original address: https://www.cnblogs.com/Halburt/p/10767389.html
The above is the detailed content of How to use dijkstra's algorithm to find the most economical travel route for May Day. For more information, please follow other related articles on the PHP Chinese website!

C++是一种广泛使用的面向对象的计算机编程语言,它支持您与之交互的大多数应用程序和网站。你需要编译器和集成开发环境来开发C++应用程序,既然你在这里,我猜你正在寻找一个。我们将在本文中介绍一些适用于Windows11的C++编译器的主要推荐。许多审查的编译器将主要用于C++,但也有许多通用编译器您可能想尝试。MinGW可以在Windows11上运行吗?在本文中,我们没有将MinGW作为独立编译器进行讨论,但如果讨论了某些IDE中的功能,并且是DevC++编译器的首选

在C++程序开发中,当我们声明了一个变量但是没有对其进行初始化,就会出现“变量未初始化”的报错。这种报错经常会让人感到很困惑和无从下手,因为这种错误并不像其他常见的语法错误那样具体,也不会给出特定的代码行数或者错误类型。因此,下面我们将详细介绍变量未初始化的问题,以及如何解决这个报错。一、什么是变量未初始化错误?变量未初始化是指在程序中声明了一个变量但是没有

C++是一门广受欢迎的编程语言,但是在使用过程中,经常会出现“未定义的引用”这个编译错误,给程序的开发带来了诸多麻烦。本篇文章将从出错原因和解决方法两个方面,探讨“未定义的引用”错误的解决方法。一、出错原因C++编译器在编译一个源文件时,会将它分为两个阶段:编译阶段和链接阶段。编译阶段将源文件中的源码转换为汇编代码,而链接阶段将不同的源文件合并为一个可执行文

C++是一门强大的编程语言,它支持使用类模板来实现代码的复用,提高开发效率。但是在使用类模板时,可能会遭遇编译错误,其中一个比较常见的错误是“无法为类模板找到实例化”(error:cannotfindinstantiationofclasstemplate)。本文将介绍这个问题的原因以及如何解决。问题描述在使用类模板时,有时会遇到以下错误信息:e

iostream头文件包含了操作输入输出流的方法,比如读取一个文件,以流的方式读取;其作用是:让初学者有一个方便的命令行输入输出试验环境。iostream的设计初衷是提供一个可扩展的类型安全的IO机制。

C++是一种流行的编程语言,它强大而灵活,适用于各种应用程序开发。在使用C++开发应用程序时,经常需要处理各种信号。本文将介绍C++中的信号处理技巧,以帮助开发人员更好地掌握这一方面。一、信号处理的基本概念信号是一种软件中断,用于通知应用程序内部或外部事件。当特定事件发生时,操作系统会向应用程序发送信号,应用程序可以选择忽略或响应此信号。在C++中,信号可以

C++是一种广泛使用的高级编程语言,它有很高的灵活性和可扩展性,但同时也需要开发者严格掌握其语法规则才能避免出现错误。其中,常见的错误之一就是“使用了未定义的命名空间”。本文将介绍该错误的含义、出现原因和解决方法。一、什么是使用了未定义的命名空间?在C++中,命名空间是一种组织可重用代码的方式,以便保持代码的模块性和可读性。使用命名空间的方式可以使同名的函数

c++初始化数组的方法:1、先定义数组再给数组赋值,语法“数据类型 数组名[length];数组名[下标]=值;”;2、定义数组时初始化数组,语法“数据类型 数组名[length]=[值列表]”。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.