-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProject_DijkstrasAlgorithm.java
407 lines (379 loc) · 16.2 KB
/
Project_DijkstrasAlgorithm.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package project_dijkstrasalgorithm;
import java.util.*;
import java.io.*;
/**
*
* @author hannahgsimon
*/
public class Project_DijkstrasAlgorithm
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner input = new Scanner(System.in);
int[][] graph = new int[0][0];
int size = 0;
int weight;
int neighbor;
int totalCost = 0;
System.out.println("Welcome to CIS265 Graph Assignment!");
int selection = 4; //arbitrary
while (selection != 0)
{
selection = 4; //arbitrary
System.out.println("""
1) Author Info
2) Load Graph
3) Traverse Graph
0) Exit Program""");
try
{
selection = input.nextInt();
if ((selection < 0) || (selection > 3))
{
System.err.println("Error; Please enter an integer 0-3.");
}
}
catch (InputMismatchException e)
{
System.err.println("Error; Please enter an integer 0-3.");
input.next();
}
input.skip(".*");
switch (selection)
{
case 1:
System.out.printf("\nAuthor Name: Hannah G. Simon\n\n");
break;
case 2:
System.err.println("Note to the person running this program: From what I can tell, file directory is different on different devices.\n"
+ "What works on my device to load in the file won't necessary work on other devices.\n"
+ "To solve this, the commented-out parts of the code can be replicated for your device to load the files in.\n");
try
{
System.out.println("Working Directory = " + System.getProperty("user.dir"));
System.out.printf("\nEnter the file name of graph you want to traverse: ");
String filename = input.next();
System.out.println(filename + " has successfully been added as the file.");
input.skip(".*");
File file = new File(System.getProperty("user.dir") + "\\src\\" + filename + ".txt");
Scanner fIn = new Scanner(file);
size = fIn.nextInt();
graph = new int[size][size];
for (int i = 0; i < graph.length; i++)
{
for (int j = 0; j < graph.length; j++)
{
graph[i][j] = -1;
}
}
System.out.println();
for (int i = 0; i < size; i++)
{
int numNeighbors = fIn.nextInt();
for (int j = 0; j < 2 * numNeighbors; j += 2)
{
weight = fIn.nextInt();
System.out.print("Weight: " + weight + " ");
neighbor = fIn.nextInt();
System.out.print("Vertex" + i + " Neighbor: " + neighbor + " ");
graph[i][neighbor] = weight;
}
System.out.println();
fIn.nextLine();
}
for (int i = 0; i < graph.length; i++)
{
for (int j = 0; j < graph[i].length; j++)
{
System.out.print(graph[i][j] + " ");
}
System.out.println();
}
// while (fIn.hasNextLine())
// {
// int i = fIn.nextInt();
// System.out.println(i);
// }
System.out.println();
fIn.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
break;
case 3:
if (size == 0)
{
System.out.println("Graph has not been loaded yet; please load graph to traverse.\n");
break;
}
int startingVertex = 0;
while (startingVertex != -1)
{
System.out.printf("\nEnter a starting vertex, -2 to find the shortest path to all other vertices, or -1 to exit the graph traversal menu: ");
boolean gotCorrect = false;
while (!gotCorrect)
{
try
{
startingVertex = input.nextInt();
if (startingVertex == -2)
{
dijkstraAlgorithmStartingVertex(graph);
gotCorrect = true;
}
else if (startingVertex == -1)
{
System.out.println("Exiting graph traversal menu.");
gotCorrect = true;
}
else if ((startingVertex < 0) || (startingVertex > size - 1))
{
System.err.println("Error; Please enter an integer between 0 and " + (size - 1));
}
else
{
System.out.println(startingVertex + " has successfully been added as the starting vertex.\n");
traverse(startingVertex, graph, totalCost);
gotCorrect = true;
}
}
catch (InputMismatchException e)
{
System.err.print("Error; Please enter an integer number.\n\n");
input.next();
}
input.skip(".*");
}
}
break;
case 0:
System.out.println("Program exited by user.");
break;
}
}
}
public static void traverse (int startingVertex, int[][] graph, int totalCost)
{
Scanner input = new Scanner(System.in);
boolean hasNeighbor = false;
ArrayList<Integer> neighbors = new ArrayList<>();
for (int i = 0; i < graph.length; i++)
{
if (graph[startingVertex][i] != -1)
{
if (graph[startingVertex][i] == graph[i][startingVertex])
{
System.out.println("Neighbor " + i + " has a cost of " + graph[startingVertex][i] + ", link is bidirectional.");
}
else
{
System.out.println("Neighbor " + i + " has a cost of " + graph[startingVertex][i] + ", link is unidirectional.");
}
neighbors.add(i);
hasNeighbor = true;
}
}
if (hasNeighbor == false)
{
System.out.println(startingVertex + " has no neighbors, cannot travel to another neighbor.");
}
if (hasNeighbor == true)
{
System.out.printf("\nPick a neighbor to travel to, or press -1 to exit this traversal: ");
boolean gotCorrect = false;
while (!gotCorrect)
try
{
int neighborSelection = input.nextInt();
if (neighborSelection == -1)
{
System.out.println("Exiting current traversal.");
gotCorrect = true;
}
else if (!neighbors.contains(neighborSelection))
{
System.err.println("Error; Please enter a valid neighbor. Options are: " + Arrays.deepToString(neighbors.toArray()));
}
else
{
System.out.println("Successfully traveled to vertex " + neighborSelection + ".");
totalCost += graph[startingVertex][neighborSelection];
System.out.printf("Total cost incurred so far is " + totalCost + "\n\n");
gotCorrect = true;
traverse(neighborSelection, graph, totalCost);
}
}
catch (InputMismatchException e)
{
System.err.println("Error; Please enter an integer number.");
input.next();
}
}
}
public static void dijkstraAlgorithmStartingVertex (int[][] graph)
{
Scanner input = new Scanner(System.in);
int startingVertex = 0;
while (startingVertex != -1)
{
System.out.printf("\nEnter a starting vertex, or -1 to exit Dijkstra's Algorithm: ");
boolean gotCorrect = false;
while (!gotCorrect)
{
try
{
startingVertex = input.nextInt();
if (startingVertex == -1)
{
System.out.println("Exiting Dijkstra's Algorithm.");
gotCorrect = true;
}
else if ((startingVertex < 0) || (startingVertex > graph.length - 1))
{
System.err.println("Error; Please enter an integer between 0 and " + (graph.length - 1));
}
else
{
System.out.println(startingVertex + " has successfully been added as the starting vertex.\n");
dijkstraAlgorithmSetup(graph, startingVertex);
gotCorrect = true;
}
}
catch (InputMismatchException e)
{
System.err.print("Error; Please enter an integer number.\n\n");
input.next();
}
input.skip(".*");
}
}
}
public static void dijkstraAlgorithmSetup (int[][] graph, int startingVertex)
{
ArrayList<Boolean> known = new ArrayList<>(graph.length);
ArrayList<Integer> cost = new ArrayList<>(graph.length);
ArrayList<Integer> path = new ArrayList<>(graph.length);
//Set<Integer> path = new HashSet<Integer>(graph.length);
for (int i = 0; i < graph.length; i++)
{
known.add(i, false);
cost.add(i, Integer.MAX_VALUE);
path.add(i, -1);
}
known.set(startingVertex, true);
cost.set(startingVertex, 0);
path.set(startingVertex, -1);
boolean hasNeighbor = false;
ArrayList<Neighbor> neighbors = new ArrayList<>();
for (int i = 0; i < graph.length; i++)
{
if (graph[startingVertex][i] != -1)
{
neighbors.add(new Neighbor(i, graph, startingVertex));
hasNeighbor = true;
}
}
if (hasNeighbor == true)
{
new Sort().selectionSortAscendingCost(neighbors);
for (int i = 0; i < neighbors.size(); i ++)
{
cost.set(neighbors.get(i).getVertex(), neighbors.get(i).getCost());
path.set(neighbors.get(i).getVertex(), startingVertex);
}
int nextVertex = neighbors.get(0).getVertex();
dijkstraAlgorithm(graph, nextVertex, known, cost, path);
}
else
{
printPath(path, cost);
}
}
public static void dijkstraAlgorithm (int[][] graph, int nextVertex, ArrayList<Boolean> known, ArrayList<Integer> cost, ArrayList<Integer> path)
{
known.set(nextVertex, true);
boolean hasNeighbor = false;
ArrayList<Neighbor> neighbors = new ArrayList<>();
for (int i = 0; i < graph.length; i++)
{
if (graph[nextVertex][i] != -1)
{
neighbors.add(new Neighbor(i, graph, nextVertex));
hasNeighbor = true;
}
}
if (hasNeighbor == true)
{
new Sort().selectionSortAscendingCost(neighbors); //unncessary step
for (int i = 0; i < neighbors.size(); i ++)
{
if (known.get(neighbors.get(i).getVertex()) == false)
{
if (neighbors.get(i).getCost() + cost.get(nextVertex) < cost.get(neighbors.get(i).getVertex()))
{
cost.set(neighbors.get(i).getVertex(), neighbors.get(i).getCost() + cost.get(nextVertex));
path.set(neighbors.get(i).getVertex(), nextVertex);
}
}
}
Boolean nextVertexExists = false;
for (int i = 0; i < known.size(); i ++) //find the false known vertex with lowest cost
{
if (known.get(i) == false && cost.get(i) != Integer.MAX_VALUE)
{
nextVertex = i;
i = known.size(); //exit for loop
nextVertexExists = true;
}
}
if (nextVertexExists == true)
{
for (int i = 0; i < known.size(); i ++) //find the false known vertex with lowest cost
{
if (known.get(i) == false && cost.get(i) != Integer.MAX_VALUE)
{
if (cost.get(i) < cost.get(nextVertex))
{
nextVertex = i;
}
}
}
dijkstraAlgorithm(graph, nextVertex, known, cost, path);
}
else
{
printPath(path, cost);
}
}
}
public static void printPath(ArrayList<Integer> path, ArrayList<Integer> cost)
{
for (int i = 0; i < path.size(); i++)
{
String pathway = String.valueOf(i) + " " + String.valueOf(path.get(i));
System.out.println("DESTINATION_NODE_" + i + ": " + getPath(path, i, pathway, cost));
}
}
public static String getPath(ArrayList<Integer> path, int vertex, String pathway, ArrayList<Integer> cost)
{
if (cost.get(vertex) == Integer.MAX_VALUE)
{
return "No Path";
}
if (path.get(vertex) == -1)
{
return String.valueOf(vertex);
}
if (path.get(path.get(vertex)) != -1)
{
pathway += " " + String.valueOf(path.get(path.get(vertex)));
return(getPath(path, path.get(vertex), pathway, cost));
}
StringBuilder pathwayReversed = new StringBuilder();
pathwayReversed.append(pathway);
pathwayReversed.reverse();
return pathwayReversed.toString();
}
}