-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBellmanFord_Algorithm.java
128 lines (97 loc) · 3.4 KB
/
BellmanFord_Algorithm.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
127
128
package Graphs;
import java.util.ArrayList;
public class BellmanFord_Algorithm {
public static class Edge{
int s;
int d;
int w;
public Edge(int w, int s, int d){
this.w = w ;
this.s = s;
this.d = d;
}
}
public static void createGraph(ArrayList<Edge>[] graph) {
for (int i = 0; i < graph.length; i++) {
graph[i] = new ArrayList<>();
}
graph[0].add(new Edge(2, 0, 1));
graph[0].add(new Edge(4, 0, 2));
graph[1].add(new Edge(-4, 1, 2));
graph[2].add(new Edge(2, 2, 3));
graph[3].add(new Edge(4, 3, 4));
graph[4].add(new Edge(-1, 4, 1));
}
public static void createGraph2(ArrayList<Edge>graph) {
graph.add(new Edge(2, 0, 1));
graph.add(new Edge(4, 0, 2));
graph.add(new Edge(-4, 1, 2));
graph.add(new Edge(2, 2, 3));
graph.add(new Edge(4, 3, 4));
graph.add(new Edge(-1, 4, 1));
}
public static void belmanFord(ArrayList<Edge>[] graph, int src){
// make dist array and make all infinity except src
int[] dist = new int[graph.length];
for (int i =0; i<graph.length; i++){
if (i != src) dist[i] = Integer.MAX_VALUE;
}
int V = graph.length;
//Vertices
for (int k = 0; k < V-1; k++){
// Edges
for (int i=0; i<graph.length; i++){
for (int e=0; e<graph[i].size(); e++){
Edge E = graph[i].get(e);
// relaxation
int u = E.s;
int v = E.d;
int w = E.w;
if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]){
dist[v] = dist[u] + w;
}
}
}
}
// print the array dist
for (int i=0; i<dist.length; i++){
System.out.print(dist[i] + " ");
}
}
public static void belmanFord_usingEdges(ArrayList<Edge> graph, int src, int V){
// make dist array and make all infinity except src
int[] dist = new int[V];
for (int i =0; i<V; i++){
if (i != src) dist[i] = Integer.MAX_VALUE;
}
//Vertices
for (int k = 0; k < V-1; k++){
// Edges
for (int e=0; e<graph.size(); e++){
Edge E = graph.get(e);
// relaxation
int u = E.s;
int v = E.d;
int w = E.w;
if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]){
dist[v] = dist[u] + w;
}
}
}
// print the array dist
for (int i=0; i<dist.length; i++){
System.out.print(dist[i] + " ");
}
}
public static void main(String[] args) {
int V = 5;
ArrayList<Edge>[] graph = new ArrayList[V];
createGraph(graph);
// Creating graph using only edges
ArrayList<Edge> graphEdges = new ArrayList<>();
createGraph2(graphEdges);
belmanFord(graph, 0);
System.out.println();
belmanFord_usingEdges(graphEdges, 0, V);
}
}