Created
December 12, 2012 23:07
-
-
Save soundsmitten/4272514 to your computer and use it in GitHub Desktop.
Java- Floyd's algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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