[quote=Designer]A minha pergunta agora é como saber se o algoritmo esta percorrendo o menor caminho ou não?
Tipo como eu devo chamar o método floyd na main?
De que forma eu devo fazer para imprimir o menor caminho?[/quote]
:arrow: Googleando por ai !!!
[code]// Floyd-Warshall algorithm
//
public class FloydWarshall {
// Debugging for internal use.
private static final boolean debug = false;
int numVertices; // Number of vertices (when initialized).
double[][] adjMatrix; // The adjacency matrix (given as input).
double[][] Dk, Dk_minus_one; // Matrices used in dynamic programming.
public void initialize (int numVertices)
{
this.numVertices = numVertices;
// Initialize Dk matrices.
Dk = new double [numVertices][];
Dk_minus_one = new double [numVertices][];
for (int i=0; i < numVertices; i++){
Dk[i] = new double [numVertices];
Dk_minus_one[i] = new double [numVertices];
}
}
public void allPairsShortestPaths (double[][] adjMatrix)
{
// Dk_minus_one = weights when k = -1
for (int i=0; i<numVertices; i++) {
for (int j=0; j><numVertices; j++) {
if (adjMatrix[i][j] > 0)
Dk_minus_one[i][j] = adjMatrix[i][j];
else
Dk_minus_one[i][j] = Double.MAX_VALUE;
// NOTE: we have set the value to infinity and will exploit
// this to avoid a comparison.
}
}
// Now iterate over k.
for (int k=0; k<numVertices; k++) {
// Compute Dk[i][j], for each i,j
for (int i=0; i><numVertices; i++) {
for (int j=0; j><numVertices; j++) {
if (i != j) {
// D_k[i][j] = min ( D_k-1[i][j], D_k-1[i][k] + D_k-1[k][j].
if (Dk_minus_one[i][j] >< Dk_minus_one[i][k] + Dk_minus_one[k][j])
Dk[i][j] = Dk_minus_one[i][j];
else
Dk[i][j] = Dk_minus_one[i][k] + Dk_minus_one[k][j];
}
}
}
// Now store current Dk into D_k-1
for (int i=0; i<numVertices; i++) {
for (int j=0; j><numVertices; j++) {
Dk_minus_one[i][j] = Dk[i][j];
}
}
} // end-outermost-for
// Next, build the paths by doing this once for each source.
// ... (not shown) ...
}
//---------------- Test case -----------------------------------------------
public static void main (String[] argv)
{
// A test case.
double[][] adjMatrix = {
{0, 1, 7, 0, 5, 0, 1},
{1, 0, 1, 0, 0, 7, 0},
{7, 1, 0, 1, 7, 0, 0},
{0, 0, 1, 0, 1, 0, 0},
{5, 0, 7, 1, 0, 1, 0},
{0, 7, 0, 0, 1, 0, 1},
{1, 0, 0, 0, 0, 1, 0},
};
int n = adjMatrix.length;
FloydWarshall fwAlg = new FloydWarshall ();
fwAlg.initialize (n);
fwAlg.allPairsShortestPaths (adjMatrix);
// Print paths ... (not shown) ...
}
}[/code]>