Dijkstra’s algorithm is fast, but limited to non-negatively weighted graph. It also does not applicable for distributed system. Bellman-Ford’s algorithm is the solution for the two problems. It is asymptotically slower than Dijkstra’s algorithm as its complexity is O(EV). However, it can solve shortest path in negatively weighted graph, and it is highly distributed. In fact, it is the basic foundation for modern internet routing.

The code is extremely simple

vector<int> bellmanford(Graph &g, int start=0){
vector<double> distance(g.V(),INF);
vector<int> parent(g.V(),-1);
distance[start]=0;
parent[start]=0;
for(int cnt=1; cnt<g.V(); cnt++){
for(int from=0; from<g.V(); from++){
for(auto e:g.adj[from]){
double dis=e.weight()+distance[from];
if(dis<distance[e.to()]){
distance[e.to()]=dis;
parent[e.to()]=from;
}
}
}
}
return parent;
}

### Like this:

Like Loading...

*Related*