You are on page 1of 4

CODIGO DEL ALGORITMO DE FLOYD WHARSALL EN JAVA CAMINOS MAS CORTOS

(código en java)

(Carga de la matriz por teclado)


(Resultados del proceso del algoritmo tabla resultante y selección de los vértices a
recorrer mostrando el camino más corto a recorrer)
CODIGO EN JAVA

import java.util.*;
public class Floyd
{
static Scanner leer=new Scanner(System.in);
public static int[][] shortestpath(int[][] adj, int[][] path)
{
int n = adj.length;
int[][] ans = new int[n][n];
copy(ans, adj);
for (int k=0; k<n;k++)
for (int i=0; i<n; i++)
for (int j=0; j<n;j++)
if (ans[i][k]+ans[k][j] < ans[i][j]) {
ans[i][j] = ans[i][k]+ans[k][j];
path[i][j] = path[k][j];
}
return ans;
}
public static void copy(int[][] a, int[][] b)
{
for (int i=0;i<a.length;i++)
for (int j=0;j<a[0].length;j++)
a[i][j] = b[i][j];
}
public static void main(String[] args)
{
Scanner stdin = new Scanner(System.in);
// Prueba el algoritmo con el gráfico mostrado en clase.
int[][] m = new int[31][31];

for (int x=0; x < m.length; x++) {


for (int y=0; y < m[x].length; y++) {
System.out.println("Introduzca el elemento [" + x + "," + y
+ "]");
m[x][y] = leer.nextInt();
}
}

int[][] shortpath;
int[][] path = new int[31][31];

for (int i=0; i<31; i++)


for (int j=0; j<31; j++)
if (m[i][j] == 10000)
path[i][j] = -1;
else
path[i][j] = i;
for (int i=0; i<31; i++)
path[i][i] = i;

shortpath = shortestpath(m, path);


// Imprime las distancias más cortas+
System.out.println(" 0 1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16 17 18 19 20 21
22 23 24 25 26 27 28 29 30");
System.out.println("
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
------------------");
for (int i=0; i<31;i++) {
System.out.print(i + " | ");
for (int j=0; j<31;j++)
System.out.print(shortpath[i][j]+" ");
System.out.println();
System.out.println();
}
System.out.println("Ruta más corta de un vértice a otro (0 a 30)");
System.out.print("Vértice inicial: ");
int start = stdin.nextInt();
System.out.print("Vértice final: ");
int end = stdin.nextInt();
String myPath = end + "";
System.out.println();
System.out.println(" 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
19 20 21 22 23 24 25 26 27 28 29 30");
System.out.println("
-----------------------------------------------------------------------------
-----");
for (int i=0; i<31;i++) {
System.out.print(i + "|");
for (int j=0; j<31;j++)
System.out.print(path[i][j]+" ");
System.out.println();
}
while (path[start][end] != start) {
myPath = path[start][end] + " -> " + myPath;
end = path[start][end];
}
myPath = start + " -> " + myPath;
System.out.println("Esta es la ruta: " + myPath);
}
}

You might also like