|
| 1 | +package algorithms.graph.shortest; |
| 2 | + |
| 3 | +/** |
| 4 | + * @author Manjunath Asundi |
| 5 | + * @see https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/# |
| 6 | + * Find all shortest paths from each vertex |
| 7 | + */ |
| 8 | +public class Floydwarshall { |
| 9 | + |
| 10 | + public static void findAllShortestPaths(int matrix[][]) { |
| 11 | + for (int k = 0; k < matrix.length; k++) |
| 12 | + for (int i = 0; i < matrix.length; i++) |
| 13 | + for (int j = 0; j < matrix[i].length; j++) |
| 14 | + if (matrix[i][k] != Integer.MAX_VALUE && matrix[k][j] != Integer.MAX_VALUE |
| 15 | + && matrix[i][k] + matrix[k][j] < matrix[i][j]) |
| 16 | + matrix[i][j] = matrix[i][k] + matrix[k][j]; |
| 17 | + printShortestPaths(matrix); |
| 18 | + } |
| 19 | + |
| 20 | + public static void printShortestPaths(int matrix[][]) { |
| 21 | + for (int i = 0; i < matrix.length; i++) { |
| 22 | + for (int j = 0; j < matrix[i].length; j++) { |
| 23 | + if (matrix[i][j] != Integer.MAX_VALUE) |
| 24 | + System.out.print(matrix[i][j] + " "); |
| 25 | + else |
| 26 | + System.out.print(-1 + " "); |
| 27 | + } |
| 28 | + System.out.println(); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + public static void main(String[] args) { |
| 33 | + findAllShortestPaths(new int[][] { { 0, 5, Integer.MAX_VALUE, 10 }, |
| 34 | + { Integer.MAX_VALUE, 0, 3, Integer.MAX_VALUE }, { Integer.MAX_VALUE, Integer.MAX_VALUE, 0, 1 }, |
| 35 | + { Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 0 } }); |
| 36 | + } |
| 37 | +} |
0 commit comments