-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFLOYDWARSHALL
More file actions
55 lines (50 loc) · 1.47 KB
/
FLOYDWARSHALL
File metadata and controls
55 lines (50 loc) · 1.47 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
51
52
53
import java.util.*;
public class FLOYDWARSHALL
{
static final int INF = 100000000; // A large value representing infinity
static void floydWarshall(int[][] dist)
{
int V = dist.length;
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] != INF && dist[k][j] != INF)
dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
}1
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of vertices: ");
int V = sc.nextInt();
int[][] dist = new int[V][V];
System.out.println("\nEnter the adjacency matrix:");
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
dist[i][j] = sc.nextInt();
}
}
//Apply Floyd–Warshall algorithm
floydWarshall(dist);
System.out.println("\nShortest distance matrix:");
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if (dist[i][j] == INF)
System.out.print("INF ");
else
System.out.print(dist[i][j] + " ");
}
System.out.println();
}
sc.close();
}
}