8. Solve All-Pairs Shortest Paths problem using Floyd's algorithm.
import java.util.*;
public class Floyd {
// Initiate infinite
static int INF = 999;
// this function consist floyd algorithm
public static void allPairShortestPath(int dist[][], int V) {
for (int k = 0; k < V; k++) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
// printing the final result
printSolution(dist, V);
}
// this function prints matrix
public static void printSolution(int graph[][], int V) {
System.out.println("The following matrix shows the shortest distances between every pair of vertices");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (graph[i][j] == INF) {
System.out.print("INF\t");
} else {
System.out.print(graph[i][j] + "\t");
}
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter no. of vertices");
int V = scan.nextInt();
int graph[][] = new int[V][V];
System.out.println("Enter vertices: ");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
graph[i][j] = scan.nextInt();
}
}
allPairShortestPath(graph, V);
}
}
NULL