FLOYD

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

EXP NO:07

Write a program to find all pair shortest path using Floyd’s algorithm.

import java.util.Scanner;

public class FloydWarshall {

private double[][] D; // Distance matrix

public FloydWarshall(int n) {

D = new double[n + 1][n + 1]; // Using 1-based indexing

public void computeShortestPaths(double[][] W, int n) {

// Initialize the distance matrix

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n; j++) {

D[i][j] = W[i][j];

// Floyd-Warshall algorithm

for (int k = 1; k <= n; k++) {

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n; j++) {

D[i][j] = Math.min(D[i][j], D[i][k] + D[k][j]);

}
public void printResults(int n) {

System.out.println("Shortest path distances between all pairs:");

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n; j++) {

if (D[i][j] == Double.POSITIVE_INFINITY) {

System.out.print("INF ");

} else {

System.out.printf("%.2f ", D[i][j]);

System.out.println();

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of vertices (n): ");

int n = scanner.nextInt();

double[][] W = new double[n + 1][n + 1]; // Weight matrix

System.out.println("Enter the weight matrix (enter INF for no connection):");

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n; j++) {

String input = scanner.next();

if (input.equalsIgnoreCase("INF")) {

W[i][j] = Double.POSITIVE_INFINITY; // No connection

} else {

W[i][j] = Double.parseDouble(input);
}

FloydWarshall floydWarshall = new FloydWarshall(n);

floydWarshall.computeShortestPaths(W, n);

floydWarshall.printResults(n);

You might also like