Floyd-Warshall

Runtime: O(V^3)

Possibly the most beautiful algorithm of all time, Floyd-Warshall finds the shortest distance between all pairs of vertices in only 4 lines of code.

Let a[i][j] be the initial distance from vertex i to vertex j. This value should be infinity if the vertices are not directly connected at the outset. (For infinity, use a value like 1 billion, because you should be able to add two infinities together.) After you run the algorithm, a[i][j] contains the shortest distance from i to j.

An important stipulation: all edge weights must be non-negative. If you have negative edge weights, consider Bellman-Ford instead.

Java
for(int k=0;k &lt; n;k++) for(int i=0;i &lt; n;i++) for(int j=0;j &lt; n;j++) a[i][j] = Math.min(a[i][j], a[i][k] + a[k][j]);