Four algorithms to solve the shortest path problem (Dijkstra+bellman-ford+spfa+floyd)

Source: Internet
Author: User

What is the shortest path problem?

In simple terms, it is the shortest path that is used to compute a node to all other nodes.

Single Source Shortest path algorithm: a known starting point, to get to other points of the quickest route.

Common algorithms: Dijkstra algorithm, Bellman-ford algorithm, SPFA algorithm

Multi-source Shortest path algorithm: Ask for a minimum of two points.

Common algorithms: Floyd algorithm

Single Source Shortest Path--dijkstra

The Dijkstra algorithm is the classic shortest path algorithm for calculating the shortest path of a node to all other nodes.

The main feature is to extend from the center of the starting point to the outer layer until it expands to the end point.

Complexity of Time: O (n^2)

Dealing with problems: single source, non-negative right, direction graph, the shortest path of graph without direction

Conditions not available: Negative weights in the edge (cannot be judged)

#defineINF 0x3f3f3f3fintE[max][max];//E[i][j] represents the distance from the I->j, not set to infinityintDis[max];//Dis[i] represents the shortest distance from the starting point to IBOOLBook[max];//Book[i] Represents whether the point I is in SintN//n verticesintS//starting pointvoidDijkstra () { for(intI=1; i<=n;i++)//initializing the DIS arraydis[i]=E[s][i];  for(intI=1; i<=n;i++)//initializing the book arraybook[i]=0; Dis[s]=0; Book[s]=1;  for(intI=1; i<=n-1; i++)//Dijkstra algorithm Core statement    {        intmindis=INF; intK//find the nearest vertex with S K         for(intj=1; j<=n;j++)        {            if(book[j]==0&& dis[j]<Mindis) {Mindis=Dis[j]; K=J; }} Book[k]=1;  for(intj=1; j<=n;j++)//the "slack" process        {            if(e[k][j]<INF) {                if(dis[j]>dis[k]+E[k][j]) dis[j]=dis[k]+E[k][j]; }        }    }}

Basic idea: To divide all the points in the weighted graph into two parts s∪u,s the set of points that have been found to be the shortest path from the starting point to the point, and the set of points in U as the shortest path. The points in U are added to S, and the shortest path is finally obtained.

How do you add a point in U to s?

① Initially, S contains only the source point S, which is s={s},dis[s]=0. U contains other vertices other than V, u={remaining vertices}, dis[u]=e[s][u] If the vertex u has an edge in S and U, otherwise, dis[u]=∞.

② a vertex k from U that has a minimum distance from the source (min (dis[])), add K to S, Dis[k] OK (think about it, the shortest path of s and K must be dis[k]=e[s][k], cannot find shorter).

③ with K as the midpoint of the new consideration, modify the distance from the source point S to the vertex of U dis[]: If the distance from the source point s to the vertex U (Dis[k]+e[k][u], through the vertex K) is shorter than the original distance (Dis[u], without the vertex K), the distance value of the vertex U is modified, The distance of the vertex k of the modified distance value plus the right on the edge. (This process is called "slack")

④ Repeat steps ② and ③ until all vertices are contained in S.

Algorithm optimization: Here each time to find the shortest distance between the point and distance, the time complexity of O (n), can be used "heap" to optimize, is the time complexity of the drop to O (LGN).

The algorithm process is detailed: http://ahalei.blog.51cto.com/4767671/1387799

Single source Shortest path--bellman-ford algorithm

Single source Shortest path, you can determine whether there is no negative power loop (if any, there is no shortest), good timeliness, time complexity O (VE).

Dealing with problems: single source, can have negative right, the direction graph, the shortest path of the graph without direction

Note: The following code is the shortest path to the graph

#defineINF 0x3f3f3f3fstructedge{intU//from    intV//End    intWeight//length}; Edge EDGE[MAXM];//used to store all the edgesintDIS[MAXN];//Dis[i] Indicates the shortest distance from the source point to IintN,m;//n points, M edgeintS//Source PointBOOLBellmen_ford () { for(intI=1; i<=n;i++)//Initializedis[i]=INF; Dis[s]=0;//source node to its own distance of 0     for(intI=1; i<n;i++)//relaxation process to calculate shortest path    {         for(intj=1; j<=m;j++)        {            if(Dis[edge[j].v]>dis[edge[j].u]+edge[j].weight)//Compare s->v and S->u->v sizesdis[edge[j].v]=dis[edge[j].u]+Edge[j].weight; }    }     for(intj=1; j<=m;j++)//determine if there is a negative edge on the right side    {        if(dis[edge[j].v]>dis[edge[j].u]+edge[j].weight)return false; }    return true;}

Basic idea: Bellman-ford thought and Dijkstra are very similar, the key point is to keep on the edge of relaxation. The biggest difference lies in the fact that the former can be used for negative edge rights. The realization of the idea is to find the shortest path, determine whether the moment can also be relaxed, if you can also relax, it is also a negative edge of the right side.

Single source Shortest path--SPFA algorithm

The previous algorithm is not good, the complexity is too high, SPFA algorithm is the Bellman-ford algorithm queue optimization, more commonly used. The SPFA algorithm can completely replace the Bellman-ford algorithm on the negative edge weight graph, and it also behaves well in sparse graphs. However, in a non-negative edge graph, in order to avoid the worst case scenario, a more efficient Dijkstra algorithm is often used, along with its use of heap-optimized versions. The usual SPFA algorithm is not satisfactory in a class of grid diagrams. Not very stable, better dijkstra.

Deal with the problem: single source, can have negative rights, the direction graph, the shortest path of the graph (in fact, can not handle the negative right)

#defineINF 0x3f3f3f3fintDis[max];//Dis[i] Indicates the shortest distance from the starting point to IBOOLVis[max];//have you visited the point IintE[max][max];//MatrixintN,m;//number of points and edgesintS//Source PointvoidSPFA () { for(intI=1; i<=n;i++)//Initialize{Dis[i]=INF; Vis[i]=false; } Queue<int>Q;    Q.push (s); Dis[s]=0; Vis[s]=true;  while(!Q.empty ()) {        intCur=Q.front ();        Q.pop (); Vis[cur]=false;  for(intI=1; i<=n;i++)        {            if(e[cur][i]!=inf&&dis[i]>=dis[cur]+E[cur][i]) {Dis[i]=dis[cur]+E[cur][i]; if(!Vis[i]) {Vis[i]=true;                Q.push (i); }            }        }    }}

Algorithm idea:

Set up a queue to save the points to be optimized, optimize each time you remove the first node of the team, and the U point the current shortest path estimate to the point of the U point to the node v relaxation operation, if the shortest path estimate of the V point is adjusted, and the V point is not in the current queue, the V points into the tail. This keeps the nodes out of the queue for relaxation operations until the queue is empty.

The algorithm process is detailed: http://www.360doc.com/content/13/1208/22/14357424_335569176.shtml

Example: http://ac.jobdu.com/problem.php?pid=1008

Multi-source Shortest path--floyd algorithm

Floyd algorithm is an algorithm for calculating the shortest path between multi-source points in weighted graphs by using the dynamic programming idea. The shortest path problem with the direction graph or negative right can be handled correctly.

Complexity of Time: O (n^3)

Space complexity: O (n^2)

Dealing with problems: multi-source, can have negative right, the direction graph, the shortest path of the graph without direction

int E[max][max];//e[i][j] represents the distance from I->j, not set to infinity int n;//n vertex//floyd algorithm void Floyd () {for    (int k=1;k<=n;k++)/ /Traverse all intermediate points     {for        (int i=1;i<=n;i++)//Traverse all the starting points         {for            (int j=1;j<=n;j++)//traverse all endpoints             {if                (E[i][j]>e[i][k]+e[k][j])//If the distance of the current i->j is greater than the distance of I->k->j                    e[i][j]=e[i][k]+e[k][j];// Update the shortest path from i->j          }}}}

Algorithm idea:

① If a transit point is not allowed, then the shortest path is our e[][] primitive matrix;

② now only allowed through the 1th vertex to relay, judging E[I][1]+E[1][J] is smaller than e[i][j], modify e[][];

③ next only allows 1 and 2nd vertices to relay ...

④ Finally, allow to pass through all the vertices of 1~n, get the last e[][], is the shortest distance between any two points required.

This is the embodiment of dynamic planning ideas. State transition equation: e[i,j]=max{e[i,k]+e[k,j],e[i,j]};

Algorithmic process: For each pair of vertices I and j, see if there is a vertex k that makes the path from I to K to J shorter than known. If it is, update it.

The algorithm process is detailed: http://ahalei.blog.51cto.com/4767671/1383613

This article refers to (including a large number of examples): http://blog.csdn.net/hjd_love_zzt/article/details/26739593

Alvinzh

Source: http://www.cnblogs.com/AlvinZH/

The copyright belongs to the author Alvinzh and blog Park all, welcome reprint and Commercial, but without the consent of the author must retain this paragraph statement, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.

Four algorithms to solve the shortest path problem (Dijkstra+bellman-ford+spfa+floyd)

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.