-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBellmanFordAlgo.java
More file actions
56 lines (46 loc) · 1.5 KB
/
Copy pathBellmanFordAlgo.java
File metadata and controls
56 lines (46 loc) · 1.5 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
import java.util.ArrayList;
public class BellmanFordAlgo {
class Edge {
int u, v, w;
Edge(int u, int v, int w) {
this.u = u;
this.v = v;
this.w = w;
}
}
void bellmanFordShortestPath(int n, ArrayList<Edge> edgeList) {
int[] dist = new int[n];
for (int i = 0; i < n; i++) dist[i] = 1000000007;
dist[0] = 0;
for (int i = 0; i < n-1; i++) {
for (Edge edge : edgeList) {
if (dist[edge.u]+edge.w < dist[edge.v]) {
dist[edge.v] = dist[edge.u]+edge.w;
}
}
}
// check for negative weight cycle
for (Edge edge : edgeList) {
if (dist[edge.u]+edge.w < dist[edge.v]) {
System.out.println("Negative weight cycle found");
break;
}
}
for (int i = 0; i < n ; i++) {
System.out.print(dist[i]+", ");
}
}
public static void main(String[] args) {
BellmanFordAlgo sPath = new BellmanFordAlgo();
int V = 6;
ArrayList<Edge> list = new ArrayList<Edge>();
list.add(sPath.new Edge(3, 2, 6));
list.add(sPath.new Edge(5, 3, 1));
list.add(sPath.new Edge(0, 1, 5));
list.add(sPath.new Edge(1, 5, -3));
list.add(sPath.new Edge(1, 2, -2));
list.add(sPath.new Edge(3, 4, -2));
list.add(sPath.new Edge(2, 4, 3));
sPath.bellmanFordShortestPath(V, list);
}
}