Dijkstra算法是处理单源最短路径的有效算法,但它局限于边的权值非负的情况,若图中出现权值为负的边,Dijkstra算法就会失效,求出的最短路径就可能是错的。这时候,就需要使用其他的算法来求解最短路径,Bellman-Ford算法就是其中最常用的一个。该算法由美国数学家理查德•贝尔曼(Richard Bellman, 动态规划的提出者)和小莱斯特•福特(Lester Ford)发明。Bellman-Ford算法的流程如下:
给定图G(V, E)(其中V、E分别为图G的顶点集与边集),源点s,
- 数组Distant[i]记录从源点s到顶点i的路径长度,初始化数组Distant[n]为, Distant[s]为0;
- 以下操作循环执行至多n-1次,n为顶点数:
- 对于每一条边e(u, v),如果Distant[u] + w(u, v) < Distant[v],则另Distant[v] = Distant[u]+w(u, v)。w(u, v)为边e(u,v)的权值;
- 若上述操作没有对Distant进行更新,说明最短路径已经查找完毕,或者部分点不可达,跳出循环。否则执行下次循环;
- 为了检测图中是否存在负环路,即权值之和小于0的环路。对于每一条边e(u, v),如果存在Distant[u] + w(u, v) < Distant[v]的边,则图中存在负环路,即是说改图无法求出单源最短路径。否则数组Distant[n]中记录的就是源点s到各顶点的最短路径长度。
可知,Bellman-Ford算法寻找单源最短路径的时间复杂度为O(V*E).
下面是该算法的伪码
procedure BellmanFord(list vertices, list edges, vertex source)
// This implementation takes in a graph, represented as lists of vertices
// and edges, and modifies the vertices so that their distance and
// predecessor attributes store the shortest paths.
// Step 1: initialize graph
for each vertex v in vertices:
if v is source then v.distance := 0
else v.distance := infinity
v.predecessor := null
// Step 2: relax edges repeatedly
for i from 1 to size(vertices)-1:
for each edge uv in edges: // uv is the edge from u to v
u := uv.source
v := uv.destination
if u.distance + uv.weight < v.distance:
v.distance := u.distance + uv.weight
v.predecessor := u
// Step 3: check for negative-weight cycles
for each edge uv in edges:
u := uv.source
v := uv.destination
if u.distance + uv.weight < v.distance:
error "Graph contains a negative-weight cycle"
#include <iostream>
#include <stack>
using namespace std;
const int maxnum=15;
const int INF=999999;
struct Edge
{
int u,v;
int weight;
};
Edge edge[maxnum];
int dist[maxnum];
int path[maxnum];
int nodesum,edgesum,source;
void Create_Graph()
{
cout<<"输入顶点数目和边数:";
cin>>nodesum>>edgesum;
for(int i=1;i<=nodesum;i++)
{
dist[i]=INF;
path[i]=-1;
}
cout<<"输入要源点:";
cin>>source;
dist[source]=0;
for(i=1;i<=edgesum;i++)
{
cout<<"输入第 "<<i<<" 条边的起点和终点还有对应的权值:";
cin>>edge[i].u>>edge[i].v>>edge[i].weight;
if(edge[i].u == source) //对和源点相邻的边的权值进行初始化
{
dist[edge[i].v]=edge[i].weight;
path[edge[i].v]=edge[i].u;
}
}
cout<<"图构建完成"<<endl;
}
bool Bellman_Ford()
{
for(int i=1;i<nodesum;i++)
{
for(int j=1;j<=edgesum;j++)
{
if(dist[edge[j].u] + edge[j].weight < dist[edge[j].v])
{
dist[edge[j].v]=dist[edge[j].u] + edge[j].weight;
path[edge[j].v]=edge[j].u;
}
}
}
//下面是判断是否含有负权回路
for(i=1;i<=edgesum;i++)
if(dist[edge[i].v] > dist[edge[i].u]+edge[i].weight)
return false;
return true;
}
void Print_Path(int v)
{
int w;
cout<<"The Shortest weight from "<<source<<" to "<<v<<" is "<<dist[v]<<endl;
cout<<"The path is: ";
stack<int> s;
w=path[v];
while(w != -1)
{
s.push(w);
w=path[w];
}
while(!s.empty())
{
cout<<s.top()<<" ";
s.pop();
}
cout<<v<<endl;
}
int main()
{
Create_Graph();
if(Bellman_Ford())
{
for(int i=2;i<=nodesum;i++)
Print_Path(i);
cout<<endl;
}
else
cout<<"oh!"<<endl;
return 0;
}
下面是一个测试
该图如下所示,但是我将各个顶点的标号按照顺时针方向标号