-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathFloyadsAlgorithm.java
More file actions
50 lines (43 loc) · 1.3 KB
/
FloyadsAlgorithm.java
File metadata and controls
50 lines (43 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
Write a program to implement All-Pairs Shortest Paths problem using Floyd's algorithm.
*/
import java.util.*;
public class FloyadsAlgorithm {
static final int MAX = 20;
static int n; //No. of vertices of G
static int G[][] = new int[MAX][MAX]; //Adjacency matrix of G
static Scanner sc = new Scanner(System.in);
public static void main(String [] args)
{
readMatrix();
floydsAlgorithm();
printMatrix();
}
static void readMatrix()
{
System.out.println("Enter the number of vertices: ");
n = sc.nextInt();
System.out.println("Enter the adjacency matrix: ");
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
G[i][j] = sc.nextInt();
}
static void floydsAlgorithm()
{
for(int k=1; k<=n; k++)
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
if(G[i][j] > G[i][k] + G[k][j])
G[i][j] = G[i][k] + G[k][j];
}
static void printMatrix()
{
System.out.println("The shortest paths are: ");
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
System.out.print(G[i][j] + " ");
System.out.println();
}
}
}