-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBellmanFord.java
244 lines (210 loc) · 7.85 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
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
//created by Xingya Ren
public class BellmanFord{
/**
* Utility class. Don't use.
*/
public class BellmanFordException extends Exception{
private static final long serialVersionUID = -4302041380938489291L;
public BellmanFordException() {super();}
public BellmanFordException(String message) {
super(message);
}
}
/**
* Custom exception class for BellmanFord algorithm
*
* Use this to specify a negative cycle has been found
*/
public class NegativeWeightException extends BellmanFordException{
private static final long serialVersionUID = -7144618211100573822L;
public NegativeWeightException() {super();}
public NegativeWeightException(String message) {
super(message);
}
}
/**
* Custom exception class for BellmanFord algorithm
*
* Use this to specify that a path does not exist
*/
public class PathDoesNotExistException extends BellmanFordException{
private static final long serialVersionUID = 547323414762935276L;
public PathDoesNotExistException() { super();}
public PathDoesNotExistException(String message) {
super(message);
}
}
private int[] distances = null;
private int[] predecessors = null;
private int source;
BellmanFord(WGraph g, int source) throws BellmanFordException{
/* Constructor, input a graph and a source
* Computes the Bellman Ford algorithm to populate the
* attributes
* distances - at position "n" the distance of node "n" to the source is kept
* predecessors - at position "n" the predecessor of node "n" on the path
* to the source is kept
* source - the source node
*
* If the node is not reachable from the source, the
* distance value must be Integer.MAX_VALUE
*
* When throwing an exception, choose an appropriate one from the ones given above
*/
/* YOUR CODE GOES HERE */
//a list of edges
//initialize distances
int numOfVertices = g.getNbNodes();
int numOfEdges = g.getEdges().size();
predecessors = new int[numOfVertices];
distances = new int[numOfVertices];
for(int i=0; i<distances.length; i++) {
distances[i] = Integer.MAX_VALUE;
}
distances[source] = 0;
//initialize predecessors
for(int i=0; i<predecessors.length; i++) {
predecessors[i] = -1; //garbage value to represent emptiness
}
for(int i=1; i<numOfVertices; i++) {
//for each edge
//relax it
for(int j=0; j<numOfEdges; j++) {
int[]nodes = g.getEdges().get(j).nodes;
int u = nodes[0]; //source of the edge
int v = nodes[1]; //destination of the edge
int weight = g.getEdges().get(j).weight;
if(((long)(distances[u])) + weight < (long)distances[v]) {
//update to shortest path
distances[v] = distances[u] + weight;
predecessors[v] = u;
}
}
}
//Check for negative-weight cycles
for(int j=0; j<numOfEdges; j++) {
int[]nodes = g.getEdges().get(j).nodes;
int u = nodes[0]; //source
int v = nodes[1]; //destination
int weight = g.getEdges().get(j).weight;
if( (long)distances[u] + weight < (long) distances[v]) {
//negative cycle, throws exception
throw new BellmanFordException("NEGATIVE CYCLE");
}
}
}
public int[] shortestPath(int destination) throws BellmanFordException{
/*Returns the list of nodes along the shortest path from
* the object source to the input destination
* If not path exists an Exception is thrown
* Choose appropriate Exception from the ones given
*/
/* YOUR CODE GOES HERE (update the return statement as well!) */
//private int[] distances = null;
//private int[] predecessors = null;
//for all edges
//check the list of predecessors --> source
if(predecessors[destination] == source) {
int shortestPath[];
shortestPath = new int[2];
shortestPath[0] = source;
shortestPath[1] = destination;
return shortestPath;
}else if (predecessors[destination] == -1) {
throw new PathDoesNotExistException("PATH DOES NOT EXIST");
}
//first add destination to the array
int shortestPath[];
shortestPath = new int[predecessors.length];
//initialize shortestPath
for(int i=0; i<shortestPath.length; i++) {
shortestPath[i] = -1;
}
int parent = predecessors[destination];
shortestPath[0] = destination; //destination added to the first slot
int i=1;
//add the parents of the destination node to this array
//if is -1 then this means the node is pointing to source
for(i=1; i<shortestPath.length; i++) {
//trace back
//add parent to the list of shortestPath
shortestPath[i] = parent;
//System.out.println("parent is:"+ parent);
//update parent
if(parent != source) {
System.out.println("parentsss:");
System.out.println(parent);
parent = predecessors[parent];
}else {
if(parent == source) {
//reached the end
//return shortestPath;
int shortestPath_CorrectLength[] = new int[i+1];
//System.out.println("i here is: "+ i);
//System.out.println("the no of nodes in a shortset path is"+ i);
for(int j=0; j<(i+1);) {
for(int k=shortestPath_CorrectLength.length-1; k>=0; k--) {
if(shortestPath[j] != -1) {
shortestPath_CorrectLength[k] = shortestPath[j];
j++;
}else {
j++;
}
}
}
}
}
}
//i is the number of steps
//System.out.println("i is "+ i);
int counter=0;
for(counter=0; counter<shortestPath.length; counter++) {
if(shortestPath[counter] == 0) {
break; //counter is the number of vertices in shortest path -1
}
}
if(parent == source) {
int numberOfNodes = counter+1;
//now we have the number of nodes in the shortest path
int shortestPath_CorrectLength[] = new int[numberOfNodes];
for(int placement=0; placement<numberOfNodes; placement++) {
shortestPath_CorrectLength[placement] = shortestPath[numberOfNodes-1-placement];
}
return shortestPath_CorrectLength;
}else {
throw new PathDoesNotExistException("PATH DOES NOT EXIST");
}
}
public void printPath(int destination){
/*Print the path in the format s->n1->n2->destination
*if the path exists, else catch the Error and
*prints it
*/
try {
int[] path = this.shortestPath(destination);
for (int i = 0; i < path.length; i++){
int next = path[i];
if (next == destination){
System.out.println(destination);
}
else {
System.out.print(next + "-->");
}
}
}
catch (BellmanFordException e){
System.out.println(e);
}
}
public static void main(String[] args){
String file = args[0];
WGraph g = new WGraph(file);
try{
BellmanFord bf = new BellmanFord(g, g.getSource());
bf.printPath(g.getDestination());
}
catch (BellmanFordException e){
System.out.println(e);
}
}
}