public class FloydWarshall {
final static int INF = 99999;
public static void floydWarshall(int[][] graph) {
int n = graph.length;
int[][] dist = new int[n][n];
// Initialize the distance matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[i][j] = graph[i][j];
}
}
// Update the shortest paths
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (dist[i][k] != INF && dist[k][j] != INF
&& dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
// Check for negative cycles
//Distance of 0 -> 0 or 1->1,etc should be ZERO but -ve cycles mei kam hota jayega.
for (int i = 0; i < n; i++) {
if (dist[i][i] < 0) {
System.out.println("Negative cycle found");
return;
}
}
// Print the shortest path matrix
printMatrix(dist);
}
public static void printMatrix(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == INF) {
System.out.print("INF ");
} else {
System.out.print(matrix[i][j] + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] graph = {
{0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};
floydWarshall(graph);
}
}