-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPaths.java
More file actions
49 lines (39 loc) · 1.43 KB
/
Paths.java
File metadata and controls
49 lines (39 loc) · 1.43 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
public class Paths {
static City[] path = new City[54];
static int sp = 0;
public static void main(String[] args) {
Map map = new Map("trains.csv");
String from = "Malmö";
String to = "Kiruna";
Integer max = 5000;
long t0 = System.nanoTime();
Integer dist = shortest(map.lookup(from), map.lookup(to), max);
long time = (System.nanoTime() - t0) / 1_000_000;
System.out.println("shorest: " + dist + " min (" + time + " ms)");
}
private static Integer shortest(City from, City to, Integer max) {
if (max < 0)
return null;
if (from == to)
return 0;
Integer shrt = null;
for (int i = 0; i < sp; i++) {
if (path[i] == from)
return null;
}
path[sp++] = from;
for (int i = 0; i < from.connections.length; i++) {
if (from.connections[i] != null) {
Connection conn = from.connections[i];
Integer distance = shortest(conn.City, to, max - conn.distanceInMinutes);
if((distance != null) && ((shrt == null) || (shrt > distance + conn.distanceInMinutes)))
shrt = distance + conn.distanceInMinutes;
if(conn.City == to && shrt<max){
max = shrt;
}
}
}
path[sp--] = null;
return shrt;
}
}