-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFloyd.java
More file actions
48 lines (48 loc) · 1.54 KB
/
Copy pathFloyd.java
File metadata and controls
48 lines (48 loc) · 1.54 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
import java.util.*;
public class Floyd
{
static final int INF = 99999;
public static void floyd(int[][] W, int n)
{
int[][] D = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
D[i][j] = W[i][j];
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if ((D[i][k] != INF && D[k][j] != INF) && (D[i][k] + D[k][j] < D[i][j]))
D[i][j] = D[i][k] + D[k][j];
System.out.println("\nShortest Distance Matrix:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
if (D[i][j] == INF)
System.out.print("INF ");
else
System.out.print(D[i][j] + " ");
System.out.println();
}
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter number of vertices: ");
int n = in.nextInt();
int[][] W = new int[n][n];
System.out.println("Enter weights for vertices(99999 for INF): ");
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
if (i == j)
{
W[i][j] = 0;
continue;
}
System.out.print((i+1) + " -> " + (j+1) + ": ");
W[i][j] = in.nextInt();
}
floyd(W, n);
in.close();
}
}