Finding the shortest path (Bellman-ford algorithm and Dijkstra algorithm)

Source: Internet
Author: User
Tags prev

Objective

The Dijkstra algorithm is an effective algorithm to deal with the shortest path of single source, but it is limited to the non-negative weight of the edge, if the weighted value is negative, the Dijkstra algorithm will fail, and the shortest path can be wrong. At this time, we need to use other algorithms to solve the shortest path, the Bellman-ford algorithm is one of the most commonly used.
In the network routing, the RIP protocol (distance vector routing algorithm) generally uses the Bellman-ford algorithm, and because of its simplicity it also applies to distributed systems, but its complexity is O (VE), which is much slower than the Dijkstra algorithm. While the OSPF protocol, link state grouping is created generally with the Dijkstra algorithm, because it is fast.

Bellman-ford algorithm
算法步骤1.初始化:将除源点外的所有顶点的最短距离估计值 dist[v] ← +∞, dist[s] ←0;2.迭代求解:反复对边集E中的每条边进行松弛操作,使得顶点集V中的每个顶点v的最短距离估计值逐步逼近其最短距离;(运行|v|-1次)3.检验负权回路:判断边集E中的每一条边的两个端点是否收敛。如果存在未收敛的顶点,则算法返回false,表明问题无解;否则算法返回true,并且从源点可达的顶点v的最短距离保存在 dist[v]中。

The algorithm uses the idea of dynamic programming and calculates the shortest path from the bottom-up way.

#include <iostream>using namespaceStdConst intMaxnum = -;Const intMaxint =99999;//Side,typedef structEdge {intU, v;//Starting point, focus    intWeight//Edge weights}edge; Edge Edge[maxnum];//Save the value of the edgeintDist[maxnum];minimum distance to source point//NodeintNodenum, Edgenum, source;//Node number, edge count, Source point                                 //initialization diagramvoidInit () {//Input node, number of sides, source pointCIN >> Nodenum >> edgenum >> source; for(inti =1; I <= nodenum;    ++i) Dist[i] = maxint; Dist[source] =0; for(inti =1; I <= edgenum; ++i) {cin >> edge[i].u >> edge[i].v >> edge[i].weight;if(edge[i].u = = Source)//Note here to set the initial conditionDIST[EDGE[I].V] = edge[i].weight; }}//Slack calculationvoidRelaxintUintVintWeight) {if(Dist[v] > Dist[u] + weight) dist[v] = Dist[u] + weight;}BOOLBellman_ford () { for(inti =1; I <= Nodenum-1; ++i) for(intj =1; J <= Edgenum; ++J) Relax (edge[j].u, EDGE[J].V, edge[j].weight);BOOLFlag =1;//Determine if there is a negative loop     for(inti =1; I <= edgenum; ++i)if(DIST[EDGE[I].V] > dist[edge[i].u] + edge[i].weight) {flag =0; Break; }returnFlag;}intMain () {init ();if(Bellman_ford ()) for(inti =1; I <= nodenum;    i++) cout << dist[i] << Endl; System"Pause");return 0;}
Dijlstra algorithm
1.初始时,S只包含起点s;U包含除s外的其他顶点,且U中顶点的距离为”起点s到该顶点的距离”[例如,U中顶点v的距离为(s,v)的长度,然后s和v不相邻,则v的距离为∞]。2.从U中选出”距离最短的顶点k”,并将顶点k加入到S中;同时,从U中移除顶点k。3.更新U中各个顶点到起点s的距离。之所以更新U中顶点的距离,是由于上一步中确定了k是求出最短路径的顶点,从而可以利用k来更新其它顶点的距离;例如,(s,v)的距离可能大于(s,k)+(k,v)的距离。4.重复步骤(2)和(3),直到遍历完所有顶点。

Refer to this blog to have a clear understanding of the Dijlstra algorithm.

#include <iostream>using namespaceStdConst intMaxnum = -;Const intMaxint =999999;voidDijkstra (intNintVint*dist,int*prev,intC[maxnum][maxnum]) {BOOLS[maxnum];//Determine if the point has been deposited into the S collection     for(intI=1; i<=n;        ++i) {Dist[i] = C[v][i]; S[i] =0;//The point has not been used initially        if(Dist[i] = = maxint) Prev[i] =0;ElsePrev[i] = v; } Dist[v] =0; S[V] =1;///dist[the node with the minimum value of the node not placed in the s set, and put it in the Union s    //Once s contains all v vertices, Dist records the shortest path length from the source point to all other vertices     for(intI=2; i<=n; ++i) {intTMP = Maxint;intU = V;//Find out the dist[j] minimum value of the currently unused point J         for(intj=1; j<=n; ++J)if((!s[j]) && dist[j]<tmp) {u = j;//U Save the number of the point with the smallest distance in the current adjacency pointTMP = Dist[j]; } S[u] =1;//means U point has been deposited in S set         //Update dist         for(intj=1; j<=n; ++J)if((!s[j]) && c[u][j]<maxint) {intNewdist = Dist[u] + c[u][j];if(Newdist < dist[j])                    {Dist[j] = newdist;                PREV[J] = u; }            }    }}voidSearchPath (int*prev,intVintu) {intQue[maxnum];inttot =1;    Que[tot] = u; tot++;intTMP = Prev[u]; while(tmp! = V)        {Que[tot] = tmp;        tot++;    TMP = prev[tmp]; } Que[tot] = V; for(intI=tot; i>=1; I.)if(I! =1) cout << Que[i] <<" ,";Elsecout << Que[i] << Endl;}intMain () {Freopen ("Input.txt","R", stdin);//Each array starts with subscript 1    intDist[maxnum];//indicates the shortest path length of the current point to the source point    intPrev[maxnum];//Record the previous node of the current point    intC[maxnum][maxnum];//Record two-point path length between graphs    intn, line;number of nodes and paths of graphs     //Input node CountCIN >> N;//input Path numberCin >> Line;intP, Q, Len;//input p, q two point and its path length     //Initialize c[][] to Maxint     for(intI=1; i<=n; ++i) for(intj=1; j<=n; ++J) C[i][j] = maxint; for(intI=1; i<=line; ++i) {cin >> p >> q >> len;if(Len < c[p][q])//with heavy edges{C[p][q] = len;//P point to QC[q][p] = len;//Q points to P, which means no graph}    } for(intI=1; i<=n; ++i) Dist[i] = maxint; for(intI=1; i<=n; ++i) { for(intj=1; j<=n; ++J) printf ("%8d", C[i][j]); printf"\ n"); } Dijkstra (N,1, Dist, Prev, c);//Shortest path lengthcout <<"The shortest path length of the source point to the last vertex:"<< Dist[n] << Endl;//Pathcout <<"The path of the source point to the last vertex is:"; SearchPath (prev,1, n);}

Finding the shortest path (Bellman-ford algorithm and Dijkstra algorithm)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.