


How to use dijkstra's algorithm to find the most economical travel route for May Day
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 ; 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(); }
The 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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

The calculation of C35 is essentially combinatorial mathematics, representing the number of combinations selected from 3 of 5 elements. The calculation formula is C53 = 5! / (3! * 2!), which can be directly calculated by loops to improve efficiency and avoid overflow. In addition, understanding the nature of combinations and mastering efficient calculation methods is crucial to solving many problems in the fields of probability statistics, cryptography, algorithm design, etc.

Multithreading in the language can greatly improve program efficiency. There are four main ways to implement multithreading in C language: Create independent processes: Create multiple independently running processes, each process has its own memory space. Pseudo-multithreading: Create multiple execution streams in a process that share the same memory space and execute alternately. Multi-threaded library: Use multi-threaded libraries such as pthreads to create and manage threads, providing rich thread operation functions. Coroutine: A lightweight multi-threaded implementation that divides tasks into small subtasks and executes them in turn.

std::unique removes adjacent duplicate elements in the container and moves them to the end, returning an iterator pointing to the first duplicate element. std::distance calculates the distance between two iterators, that is, the number of elements they point to. These two functions are useful for optimizing code and improving efficiency, but there are also some pitfalls to be paid attention to, such as: std::unique only deals with adjacent duplicate elements. std::distance is less efficient when dealing with non-random access iterators. By mastering these features and best practices, you can fully utilize the power of these two functions.

In C language, snake nomenclature is a coding style convention, which uses underscores to connect multiple words to form variable names or function names to enhance readability. Although it won't affect compilation and operation, lengthy naming, IDE support issues, and historical baggage need to be considered.

The release_semaphore function in C is used to release the obtained semaphore so that other threads or processes can access shared resources. It increases the semaphore count by 1, allowing the blocking thread to continue execution.

Dev-C 4.9.9.2 Compilation Errors and Solutions When compiling programs in Windows 11 system using Dev-C 4.9.9.2, the compiler record pane may display the following error message: gcc.exe:internalerror:aborted(programcollect2)pleasesubmitafullbugreport.seeforinstructions. Although the final "compilation is successful", the actual program cannot run and an error message "original code archive cannot be compiled" pops up. This is usually because the linker collects

The main reasons for MySQL installation failure are: 1. Permission issues, you need to run as an administrator or use the sudo command; 2. Dependencies are missing, and you need to install relevant development packages; 3. Port conflicts, you need to close the program that occupies port 3306 or modify the configuration file; 4. The installation package is corrupt, you need to download and verify the integrity; 5. The environment variable is incorrectly configured, and the environment variables must be correctly configured according to the operating system. Solve these problems and carefully check each step to successfully install MySQL.
