Bellman-Ford

Runtime: O(E*V)

Bellman-Ford is a single-source shortest path algorithm, usually used when there are negative edge weights in the graph. If there are no negative edge weights, consider using Dijkstra's algorithm instead.

Bellman-Ford can also be used as a negative-weight cycle detection algorithm. To do so, create a new dummy vertex that has edges to all other vertices with weight 0, and run the algorithm with the dummy vertex as the source.

Let n be the number of vertices.

Let s be the source vertex.

Let d[] be an array where d[i] is the shortest distance to vertex i from the source.

Let p[] be an array where p[i] is the predecessor of vertex i. This array can be used to reconstruct the shortest path.

Let e[] be an array of Edge objects, where each Edge holds three integers, (u,v,w), if the edge is from vertex u to vertex v with weight w.

Java
int[] d = new int[n]; Arrays.fill(d, 1000000000); d[s] = 0; int[] p = new int[n]; Arrays.fill(p, -1); Edge[] e; //Fill this with edges //Relax weights n-1 times for(int i=0;i &lt; n-1;i++) { 	for(int j=0;j &lt; e.length;j++) { 		int u = e[j].u; 		int v = e[j].v; 		int w = e[j].w; 		if(d[u] + w &lt; d[v]) { 			d[v] = d[u] + w; 			p[v] = u; 		} } } //Check for negative-weight cycles boolean negcycle = false; for(int i=0;i &lt; e.length;i++) { 	int u = e[i].u; 	int v = e[i].v; 	int w = e[i].w; 	if(d[u] + w &lt; d[v]) negcycle = true; }