From b4e14bab3bc1a3ab02f0a03087888c1dc5020504 Mon Sep 17 00:00:00 2001 From: "N.Sai Sujith" Date: Wed, 15 Oct 2025 23:26:17 +0530 Subject: [PATCH] Add Floyd-Warshall algorithm in Java with example usage --- FloydWarshall.java | 52 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 FloydWarshall.java diff --git a/FloydWarshall.java b/FloydWarshall.java new file mode 100644 index 000000000000..d58d0432958b --- /dev/null +++ b/FloydWarshall.java @@ -0,0 +1,52 @@ +// FloydWarshall.java +import java.util.Arrays; + +public class FloydWarshall { + + static final int INF = 99999; + + public static void floydWarshall(int[][] graph) { + int V = graph.length; + int[][] dist = new int[V][V]; + + // Initialize distance array + for (int i = 0; i < V; i++) { + dist[i] = Arrays.copyOf(graph[i], V); + } + + // Core 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] + dist[k][j] < dist[i][j]) { + dist[i][j] = dist[i][k] + dist[k][j]; + } + } + } + } + + printSolution(dist); + } + + static void printSolution(int[][] dist) { + System.out.println("Shortest distance between every pair:"); + for (int i = 0; i < dist.length; i++) { + for (int j = 0; j < dist.length; j++) { + if (dist[i][j] == INF) System.out.print("INF "); + else System.out.print(dist[i][j] + " "); + } + System.out.println(); + } + } + + public static void main(String[] args) { + int[][] graph = { + {0, 3, INF, 7}, + {8, 0, 2, INF}, + {5, INF, 0, 1}, + {2, INF, INF, 0} + }; + + floydWarshall(graph); + } +} \ No newline at end of file