Skip to content

Instantly share code, notes, and snippets.

@soundsmitten
Created December 12, 2012 23:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save soundsmitten/4272514 to your computer and use it in GitHub Desktop.
Save soundsmitten/4272514 to your computer and use it in GitHub Desktop.
Java- Floyd's algorithm
// Wikipedia: a graph analysis algorithm for finding shortest paths in a weighted graph
// (with positive or negative edge weights) and also for finding transitive closure of a
// relation R. A single execution of the algorithm will find the lengths (summed weights)
// of the shortest paths between all pairs of vertices, though it does not return details
// of the paths themselves. The algorithm is an example of dynamic programming.
public void floyd(int n, int[][] W, int[][] P, int[][] D)
{
D = W;
for (int i = 0; i<n; i++)
for(j = 0; j<n; j++)
P[i][j] = 0;
for (int k = 0; k < n; k++)
for(int i = 0; i < n; i++)
for(int j = 0; j<n; j++)
{
if (D[i][k] + D[k][j]< D[i][j])
{
D[i][j] = D[i][k] + D[k][j]
P[i][j] = k
}
}
}
public void path(int q, int r)
{
path (q, P[q][r]);
System.out.println("v" + P[q][r]);
path (P[q][r], r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment