This repository has been archived by the owner on Nov 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dijkstra.java
104 lines (76 loc) · 2.13 KB
/
Dijkstra.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
/*
* Name: Adam Kaplan
*
* NetID: akaplan6
*
* Project: #4
*
* Lab Section: TR 4:50PM - 6:05PM (I switched my lab section)
*
* TA: Charlie Kelman
*
* I affirm that I have not given or received any unauthorized help on this assignment, and that this work is my own.
*/
import java.util.Collections;
import java.util.LinkedList;
import java.util.PriorityQueue;
public class Dijkstra {
Graph g;
double traveled;
public Dijkstra(Graph g){
this.g = g;
traveled = 0;
}
private void doDijkstra(Vertex from, Vertex to){
Vertex source = g.vertexList.get(from.id);
PriorityQueue<Vertex> q = new PriorityQueue<Vertex>();
q.addAll(g.vertexList.values());
q.remove(source);
source.distance = 0;
q.add(source);
while(!q.isEmpty()){
// Get the minimum Vertex
Vertex v = g.vertexList.get(q.poll().id);
for(Edge e : v.adjacentEdges){
Vertex w = g.vertexList.get(e.to.id);
if(q.contains(w)){
if(v.distance + e.weight < g.vertexList.get(w.id).distance){
q.remove(g.vertexList.get(w.id));
g.vertexList.get(w.id).distance = v.distance + e.weight;
g.vertexList.get(w.id).previous = v;
q.add(g.vertexList.get(w.id));
}
}
}
}
}
public LinkedList<Vertex> getShortestPathVertices(Vertex from, Vertex to){
doDijkstra(from, to);
LinkedList<Vertex> path = new LinkedList<Vertex>();
for(Vertex v = to; v != null; v = v.previous){
path.add(v);
traveled += v.distance;
}
Collections.reverse(path);
return path;
}
public LinkedList<Edge> getShortestPathEdges(Vertex from, Vertex to){
LinkedList<Vertex> vertices = getShortestPathVertices(from, to);
LinkedList<Edge> edges = new LinkedList<Edge>();
Vertex[] verticesArray = vertices.toArray(new Vertex[vertices.size()]);
for(int i = 0; i < verticesArray.length-1; i++){
Edge adjacentEdge = null;
for(Edge e : verticesArray[i].adjacentEdges){
if(e.to.equals(verticesArray[i+1])){
adjacentEdge = e;
break;
}
}
edges.add(adjacentEdge);
}
return edges;
}
public double getTraveled(){
return traveled * 3;
}
}