-
Notifications
You must be signed in to change notification settings - Fork 275
Expand file tree
/
Copy pathRouteCalculator.java
More file actions
84 lines (68 loc) · 2.82 KB
/
Copy pathRouteCalculator.java
File metadata and controls
84 lines (68 loc) · 2.82 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
package subway.controller;
import java.util.List;
import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.WeightedMultigraph;
import subway.domain.Line;
import subway.domain.LineRepository;
import subway.domain.Station;
import subway.view.OutputView;
public class RouteCalculator {
Station stationDeparture;
Station stationArrival;
String option;
int totalTime = 0;
int totalDistance = 0;
public RouteCalculator(Station stationDeparture, Station stationArrival, String option) {
this.stationDeparture = stationDeparture;
this.stationArrival = stationArrival;
this.option = option;
try {
if (option.equals("1")) {
getDijkstraShortestPathByDistance();
return;
}
if (option.equals("2")) {
getDijkstraShortestPathByTime();
return;
}
} catch (NullPointerException e) {
OutputView.showErrorStationUnreachable();
}
}
public void getDijkstraShortestPathByDistance() {
WeightedMultigraph<Station, DefaultWeightedEdge> graph = new WeightedMultigraph(
DefaultWeightedEdge.class);
for (Line line : LineRepository.lines()) {
graph.addVertex(line.getStations().get(0));
for (int i = 1; i < line.getStations().size(); i++) {
graph.addVertex(line.getStations().get(i));
graph.setEdgeWeight(
graph.addEdge(line.getStations().get(i - 1), line.getStations().get(i)),
line.getDistances().get(i - 1));
}
}
calculateShortestPath(graph);
}
public void getDijkstraShortestPathByTime() {
WeightedMultigraph<Station, DefaultWeightedEdge> graph = new WeightedMultigraph(
DefaultWeightedEdge.class);
for (Line line : LineRepository.lines()) {
graph.addVertex(line.getStations().get(0));
for (int i = 1; i < line.getStations().size(); i++) {
graph.addVertex(line.getStations().get(i));
graph.setEdgeWeight(
graph.addEdge(line.getStations().get(i - 1), line.getStations().get(i)),
line.getTimes().get(i - 1));
}
}
calculateShortestPath(graph);
}
public void calculateShortestPath(WeightedMultigraph graph) {
DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(graph);
List<Station> shortestPath = dijkstraShortestPath.getPath(stationDeparture, stationArrival)
.getVertexList();
totalTime = (int) dijkstraShortestPath.getPathWeight(stationDeparture, stationArrival);
OutputView.showResult(shortestPath, totalDistance, totalTime);
}
}