-
Notifications
You must be signed in to change notification settings - Fork 0
/
BellmanFord.java
55 lines (55 loc) · 1.58 KB
/
BellmanFord.java
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
import java.util.*;
public class BellmanFord {
static class Node{
private int v,u,wt;
Node(int u,int v,int wt){
this.u=u;
this.v=v;
this.wt=wt;
}
Node(){}
int getU(){return u;}
int getV(){return v;}
int getWt(){return wt;}
}
static void bellmanFordAlgo(ArrayList<Node>Edges,int V,int src){
int []dist=new int[V];
for(int i=0;i<V;i++)dist[i]=Integer.MAX_VALUE;
dist[src]=0;
for(int i=0;i<V-1;i++){
for(Node node:Edges){
if(dist[node.getU()]+node.wt<dist[node.getV()])
dist[node.getV()]=dist[node.getU()]+node.wt;
}
}
// detect negative cycle
boolean flag=false;
for(Node node:Edges){
if(dist[node.getU()]+node.wt<dist[node.getV()]) {
dist[node.getV()] = dist[node.getU()] + node.wt;
System.out.println("Negative Cycle");
flag=true;
break;
}
}
if(flag==false)
{
for(int i = 0;i<V;i++) {
System.out.println(i + " " + dist[i]);
}
}
}
public static void main(String[] args) {
ArrayList<Node>adj=new ArrayList<>();
//assignment ques 1
int V=5;
adj.add(new Node(0,1,-1));
adj.add(new Node(0,2,4));
adj.add(new Node(1,2,3));
adj.add(new Node(1,3,2));
adj.add(new Node(1,4,2));
adj.add(new Node(3,1,1));
adj.add(new Node(4,3,-3));
bellmanFordAlgo(adj,V,0);
}
}