-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstra.java
More file actions
93 lines (79 loc) · 2.7 KB
/
Dijkstra.java
File metadata and controls
93 lines (79 loc) · 2.7 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
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
import java.io.*;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.ArrayList;
class Vertex implements Comparable<Vertex> {
public int key;
public ArrayList<Edge> edges;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex(int key) {
this.key = key;
edges = new ArrayList<Edge>();
}
public int compareTo(Vertex other) {
return Double.compare(minDistance, other.minDistance);
}
}
class Edge {
public Vertex target;
public double weight;
public Edge(Vertex t, double w) {
target = t;
weight = w;
}
}
public class Dijkstra {
public static void shortestPath(Vertex source) {
source.minDistance = 0.0;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();
for (Edge e : u.edges) {
Vertex v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance) {
vertexQueue.remove(v);
v.minDistance = distanceThroughU;
vertexQueue.add(v);
}
}
}
}
public static void main(String[] args) {
HashMap<Integer, Vertex> nodes = new HashMap<Integer, Vertex>();
try {
BufferedReader br = new BufferedReader(new FileReader("data/DijkstraData.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String[] arr = line.split("\t");
Vertex v;
int key = Integer.parseInt(arr[0]);
if (nodes.containsKey(key)) {
v = nodes.get(key);
} else {
v = new Vertex(key);
nodes.put(key, v);
}
for (int i = 1; i < arr.length; i++) {
String[] tmp = arr[i].split(",");
key = Integer.parseInt(tmp[0]);
Vertex ve;
if (nodes.containsKey(key)) {
ve = nodes.get(key);
} else {
ve = new Vertex(key);
nodes.put(key, ve);
}
Edge edge = new Edge(ve, Double.parseDouble(tmp[1]));
v.edges.add(edge);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
// Find shortest path from node 1 to other nodes
shortestPath(nodes.get(1));
}
}