|
| 1 | +/* |
| 2 | + * Floyd-Warshall algorithm in Java |
| 3 | + * All pairs shortest path algorithm |
| 4 | + * Time Complexity: O(n³) |
| 5 | + * Space Complexity: O(n²) |
| 6 | +*/ |
| 7 | + |
| 8 | +public class FloydWarshall { |
| 9 | + |
| 10 | + public static void showMatrix(long[][] matriz, int nroVertices) { |
| 11 | + for (int i = 0; i < nroVertices; i++) { |
| 12 | + for (int j = 0; j < nroVertices; j++) { |
| 13 | + if (matriz[i][j] < 10) |
| 14 | + System.out.print(" " + matriz[i][j] + " "); |
| 15 | + else |
| 16 | + System.out.print(matriz[i][j] + " "); |
| 17 | + } |
| 18 | + System.out.println(); |
| 19 | + } |
| 20 | + System.out.println(); |
| 21 | + } |
| 22 | + |
| 23 | + public static void main(String[] args) { |
| 24 | + int nroVertices = 5; |
| 25 | + long[][] matriz = { |
| 26 | + { 0, 2, 10, 5, 7 }, |
| 27 | + { 2, 0, 3, 3, 1 }, |
| 28 | + { 10, 3, 0, 1, 2 }, |
| 29 | + { 5, 3, 1, 0, Long.MAX_VALUE }, |
| 30 | + { 7, 1, 2, 2, 0 } |
| 31 | + }; |
| 32 | + |
| 33 | + // Display the original matrix |
| 34 | + System.out.println("Original matrix:"); |
| 35 | + showMatrix(matriz, nroVertices); |
| 36 | + |
| 37 | + floydWarshall(matriz, nroVertices); |
| 38 | + |
| 39 | + // Display the updated matrix |
| 40 | + System.out.println("Updated matrix:"); |
| 41 | + showMatrix(matriz, nroVertices); |
| 42 | + |
| 43 | + // Show all shortest paths |
| 44 | + System.out.println(); |
| 45 | + for (int i = 0; i < nroVertices; i++) { |
| 46 | + for (int x = 0; x < nroVertices; x++) { |
| 47 | + System.out.println("Shortest distance from " + i + " to " + x + " = " + matriz[x][i] + "."); |
| 48 | + } |
| 49 | + } |
| 50 | + System.out.println(); |
| 51 | + } |
| 52 | + |
| 53 | + public static void floydWarshall(long[][] matriz, int n) { |
| 54 | + for (int x = 0; x < n; x++) { // Intermediary vertex |
| 55 | + for (int y = 0; y < n; y++) { // Origin vertex |
| 56 | + for (int z = 0; z < n; z++) { // Destination vertex |
| 57 | + if (matriz[y][z] > (matriz[y][x] + matriz[x][z])) { |
| 58 | + matriz[y][z] = matriz[y][x] + matriz[x][z]; |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments