-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBellman_Ford_Algo.java
126 lines (104 loc) · 2.42 KB
/
Bellman_Ford_Algo.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
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/**
*
* @author pulkit4tech
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
// Bellman Ford Algorithm for src to all vertices
// shortest distance even with negative wt. (not possible with dijkstra)
class Bellman_Ford_Algo implements Runnable {
BufferedReader c;
PrintWriter pout;
// static long mod = 1000000007;
public void run() {
try {
c = new BufferedReader(new InputStreamReader(System.in));
pout = new PrintWriter(System.out, true);
solve();
pout.close();
} catch (Exception e) {
pout.close();
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) throws Exception {
new Thread(new Bellman_Ford_Algo()).start();
}
void solve() throws Exception {
bellmanford();
}
private void bellmanford() {
Graph g = new Graph(5, 8);
g.addEdge(0, 1, -1);
g.addEdge(0, 2, 4);
g.addEdge(1, 2, 3);
g.addEdge(1, 2, 3);
g.addEdge(1, 4, 2);
g.addEdge(3, 2, 5);
g.addEdge(3, 1, 1);
g.addEdge(4, 3, -3);
g.BellmanFord_Algo(g, 0);
}
class Graph {
class Edge {
int src, dest, wt;
Edge() {
src = dest = wt = 0;
}
}
int V, E, countEdge;
Edge edge[];
Graph(int v, int e) {
V = v;
E = e;
countEdge = 0;
edge = new Edge[E];
for (e--; e >= 0; e--) {
edge[e] = new Edge();
}
}
void BellmanFord_Algo(Graph g, int src) {
int V = g.V, E = g.E;
int dist[] = new int[V];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;
for (int i = 1; i < V; i++) {
for (int j = 0; j < E; j++) {
int u = g.edge[j].src;
int v = g.edge[j].dest;
int wt = g.edge[j].wt;
if (dist[u] != Integer.MAX_VALUE && dist[u] + wt < dist[v]) {
dist[v] = dist[u] + wt;
}
}
}
// checking for negative wt cycle
for (int i = 0; i < E; i++) {
int u = g.edge[i].src;
int v = g.edge[i].dest;
int wt = g.edge[i].wt;
if (dist[u] != Integer.MAX_VALUE && dist[u] + wt < dist[v]) {
pout.println("Graph contain negative weight cycle");
}
}
printArr(dist, src);
}
void printArr(int dist[], int src) {
pout.println("Vertex Distance");
for (int i = 0; i < V; i++) {
pout.println(i + "\t\t" + dist[i]);
}
}
void addEdge(int src, int dest, int wt) {
if (countEdge < E) {
edge[countEdge].src = src;
edge[countEdge].dest = dest;
edge[countEdge].wt = wt;
countEdge++;
}
}
}
}