-
Notifications
You must be signed in to change notification settings - Fork 0
/
bellman Ford Algorithm
68 lines (67 loc) · 1.49 KB
/
bellman Ford Algorithm
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
import java.util.*;
class Node{
int v;int u; int w ;
Node(int u,int v,int w)
{
this.u = u;
this.v = v;
this.w = w;
}
Node(){}
int getV()
{return v;}
int getU()
{return u;}
int getWeigth()
{return w;}
}
public class BellmanFord {
static void bellmanFord(ArrayList<Node> a, int[] dis)
{
for(int i=0;i<5;i++)
{
for(Node it:a)
{
if(dis[it.getU()]+ it.getWeigth()<dis[it.getV()])
{
dis[it.getV()] = dis[it.getU()]+ it.getWeigth();
}
}
}
int mc = 0;
for(Node it:a)
{
if(dis[it.getU()]+ it.getWeigth()<dis[it.getV()])
{
mc=1;
System.out.println("Negative cycle");
break;
}
}
if(mc==0)
{
for(int i=0;i<6;i++)
{
System.out.print(dis[i]+" ");
}
}
}
public static void main(String arg[])
{
ArrayList<Node> a = new ArrayList<Node>();
a.add(new Node(3,2,6));
a.add(new Node(5,3,1));
a.add(new Node(0,1,5));
a.add(new Node(1,5,-3));
a.add(new Node(1,2,-2));
a.add(new Node(3,4,-2));
a.add(new Node(2,4,3));
int dis[]=new int[6];
for(int i=0;i<6;i++)
{
dis[i]=100000000;
}
dis[0]=0;
bellmanFord(a,dis);
}
}