-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstraAlg.java
More file actions
54 lines (43 loc) · 1.27 KB
/
Copy pathDijkstraAlg.java
File metadata and controls
54 lines (43 loc) · 1.27 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
import java.util.HashMap;
import java.util.PriorityQueue;
public class DijkstraAlg {
private HashMap<String, vertex> graph;
private String start;
public DijkstraAlg(HashMap<String, vertex> graph, String start) {
this.graph = graph;
this.start = start;
}
public HashMap<String, vertex> solve() {
//initilize sources
vertex first = this.graph.get(start);
first.dist = 0.0;
//add start to the queue
PriorityQueue<vertex> Q = new PriorityQueue<>();
Q.add(this.graph.get(start));
while (!Q.isEmpty()) {
//extract min
vertex u = Q.poll();
for (connect v : u.edges) {
//vertex v
vertex V = this.graph.get(v.vertex);
if (relax(u, v)) {
if (Q.contains(V)) {
Q.remove(V);
}
Q.add(V);
}
}
}
return this.graph;
}
public boolean relax(vertex u, connect v) {
double w = v.weight;
vertex V = this.graph.get(v.vertex);
if (V.dist > u.dist + w) {
V.dist = u.dist + w;
V.pi = u.name;
return true;
}
return false;
}
}