forked from striver79/StriversGraphSeries
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BellmanFordJava
71 lines (55 loc) · 1.41 KB
/
BellmanFordJava
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
import java.util.*;
class Node
{
private int u;
private int v;
private int weight;
Node(int _u, int _v, int _w) { u = _u; v = _v; weight = _w; }
Node() {}
int getV() { return v; }
int getU() { return u; }
int getWeight() { return weight; }
}
class Main
{
void bellmanFord(ArrayList<Node> edges, int N, int src)
{
int dist[] = new int[N];
for(int i = 0;i<N;i++) dist[i] = 10000000;
dist[src] = 0;
for(int i = 1;i<=N-1;i++) {
for(Node node : edges) {
if(dist[node.getU()] + node.getWeight() < dist[node.getV()]) {
dist[node.getV()] = dist[node.getU()] + node.getWeight();
}
}
}
int fl = 0;
for(Node node: edges) {
if(dist[node.getU()] + node.getWeight() < dist[node.getV()]) {
fl = 1;
System.out.println("Negative Cycle");
break;
}
}
if(fl == 0) {
for(int i = 0;i<N;i++) {
System.out.println(i + " " + dist[i]);
}
}
}
public static void main(String args[])
{
int n = 6;
ArrayList<Node> adj = new ArrayList<Node>();
adj.add(new Node(3, 2, 6));
adj.add(new Node(5, 3, 1));
adj.add(new Node(0, 1, 5));
adj.add(new Node(1, 5, -3));
adj.add(new Node(1, 2, -2));
adj.add(new Node(3, 4, -2));
adj.add(new Node(2, 4, 3));
Main obj = new Main();
obj.bellmanFord(adj, n, 0);
}
}