Home > Article > Backend Development > Implement Dijkstra's algorithm for the shortest path using C++
The link state routing algorithm (LS algorithm) of the network layer, one of which is written using the Dijkstra algorithm . Introduction to "Introduction to Algorithms": Dijkstra's algorithm solves the single-source shortest path problem on a weighted directed graph. This algorithm requires that the weights of all edges are non-negative.
Algorithm idea
As shown in the figure, there are 6 points and 8 edges V={ 1,2,3,4,5,6}
4. By path From the array, we can know that V concentration point 2 has the shortest path (value is 3) at this time, so let u=2, then S={1,2}, V={3,4,5,6}
Because dis[3]=dis[2] 4 ⇒ 7=3 4
… . dis[5]=dis[2] 9 ⇒ 12=3 9
Because dis[5]=12>dis[3] 1=7 1 ⇒ Let dis[5]=dis[3] 1=7 1=8
because dis[6]=∞ >dis[3] 6= 7 6 ⇒ Let dis[6]=dis[6] 6=7 6=13
The shortest path from point 1 to each point as above Just figure out the path. I feel like the writing lately is very messy and not easy to understand. But thank you all for being able to see this.
Now is the time to post the code
/* * @author Wenpupil * @time 2019-04-04 * @version 1.0 * @Description 最短路径之Dijkstra算法 关于无负权的无向图练习 */ #include<iostream> #include<cmath> #include<string.h> #define INIT 9999 using namespace std; int map[20][20]; //存储19个点的无向图 int s[20]; //标记数组 int dis[20]; void mDijkstra(int i,int m) { for(int i=0;i0){ dis[j]=min(dis[j],dis[u]+map[u][j]); } } } } int main(void) { int m,n; //共有m个点,n条边 cin>>m>>n; for(int i=0;i<n int cin>>x>>y>>z; map[x][y]=map[y][x]=z; } mDijkstra(1,m); //从节点1出发 遍历全图 for(int i=1;i<br><link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-258a4616f7.css" rel="stylesheet"> <!-- flowchart 箭头图标 勿删 --><svg xmlns="http://www.w3.org/2000/svg" style="display: none;"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>##[Recommended course: </svg><h2> <span style="font-size: 16px;"> C video tutorial</span><a href="http://www.php.cn/course/list/38.html" target="_self" style="font-size: 16px; text-decoration: underline;"><span style="font-size: 16px;">】</span></a> </h2></n></string.h></cmath></iostream>
The above is the detailed content of Implement Dijkstra's algorithm for the shortest path using C++. For more information, please follow other related articles on the PHP Chinese website!