-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBellmanFord.java
More file actions
87 lines (82 loc) · 2.34 KB
/
BellmanFord.java
File metadata and controls
87 lines (82 loc) · 2.34 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import java.util.Scanner;
public class BellmanFord
{
private int d[];
private int num_ver;
public static final int max = 999;
public BellmanFord(int num_ver)
{
this.num_ver = num_ver;
d=new int[num_ver+1];
}
public void bellmanfordevaluation(int source, int a[][])
{
for(int node=1;node<=num_ver;node++)
{
d[node]= max;
}
d[source] = 0;
for(int node=1;node<num_ver;node++)
{
for(int sn=1;sn<=num_ver;sn++)
{
for(int dn=1;dn<=num_ver;dn++)
{
if(a[sn][dn]!=max)
{
if(d[dn]>d[sn]+a[sn][dn])
d[dn] = d[sn] + a[sn][dn];
}
}
}
}
for(int sn=1;sn<=num_ver;sn++)
{
for(int dn=1;dn<=num_ver;dn++)
{
if(d[dn]>d[sn] + a[sn][dn])
System.out.println("The graph contains negative edges");
}
}
for(int vertex =1;vertex<=num_ver;vertex++)
{
System.out.println("Distance of source "+source+" to "+vertex+" is "+d[vertex]);
}
}
public static void main(String [] args)
{
int num_ver=0;
int source;
Scanner PD = new Scanner(System.in);
System.out.println("Enter the number of Vertices");
num_ver = PD.nextInt();
int a[][] = new int[num_ver+1][num_ver+1];
System.out.println("Enter the adjacency matrix");
for (int sn=1;sn<=num_ver;sn++)
{
for(int dn=1;dn<=num_ver;dn++)
{
if(sn==dn)
{
a[sn][dn]=0;
System.out.println(">> 0");
continue;
}
else
{
a[sn][dn] = PD.nextInt();
if(a[sn][dn] == 0)
{
a[sn][dn]=max;
continue;
}
}
}
}
System.out.println("Enter the source vertex");
source = PD.nextInt();
BellmanFord B = new BellmanFord(num_ver);
B.bellmanfordevaluation(source,a);
PD.close();
}
}