Bellman-Ford’s Algorithm

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;	
}

Advertisements
This entry was posted in Algorithms, Computer Science and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s