diff --git a/Floyd Warshall algorithm #38 b/Floyd Warshall algorithm #38 new file mode 100644 index 0000000..fcd9ae0 --- /dev/null +++ b/Floyd Warshall algorithm #38 @@ -0,0 +1,50 @@ +public class FloydWarshallAlgorithm { + public static void floydWarshall(int[][] graph) { + int V = graph.length; + int[][] dist = new int[V][V]; + + // Initialize the distance matrix with the graph + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { + dist[i][j] = graph[i][j]; + } + } + + // Perform the Floyd-Warshall algorithm + for (int k = 0; k < V; k++) { + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { + if (dist[i][k] != Integer.MAX_VALUE && dist[k][j] != Integer.MAX_VALUE && + dist[i][k] + dist[k][j] < dist[i][j]) { + dist[i][j] = dist[i][k] + dist[k][j]; + } + } + } + } + + // Print the shortest path distances + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { + if (dist[i][j] == Integer.MAX_VALUE) { + System.out.print("INF\t"); + } else { + System.out.print(dist[i][j] + "\t"); + } + } + System.out.println(); + } + } + + public static void main(String[] args) { + int V = 4; // Number of vertices + + int[][] graph = { + {0, 3, Integer.MAX_VALUE, 0}, + {Integer.MAX_VALUE, 0, 2, Integer.MAX_VALUE}, + {Integer.MAX_VALUE, Integer.MAX_VALUE, 0, 1}, + {8, Integer.MAX_VALUE, Integer.MAX_VALUE, 0} + }; + + floydWarshall(graph); + } +}