Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Returns the path between two cities with the minimum cost
- *
- * @param from the departing city
- * @param to the destination city
- * @return path
- */
- public LinkedList<Spot> minimumCost(Spot from, Spot to) {
- Spot initial = from;
- LinkedList<Spot> path = new LinkedList<>();
- path.add(from);
- Set<Spot> visited = new HashSet<>();
- visited.add(from);
- Spot add = new Spot();
- int aux, cost;
- while (!(from.equals(to))) {
- aux = 0;
- if (((Set) map.directConnections(from)).contains(to)) {
- path.add(to);
- from = to;
- }
- if (!(from.equals(to))) {
- if (verIfAllVisitedOrNoConnections(((Set) map.directConnections(from)), visited, from, initial)) {
- for (Spot s : map.directConnections(from)) {
- if (!(visited.contains(s))) {
- cost = map.getEdge(from, s).getCost();
- if (aux == 0) {
- aux = cost;
- add = s;
- }
- if (cost < aux) {
- aux = cost;
- add = s;
- }
- }
- }
- path.add(add);
- visited.add(add);
- from = add;
- } else {
- visited.add(from);
- path.remove(from);
- from = initial;
- }
- }
- }
- return path;
- }
- private boolean verIfAllVisitedOrNoConnections(Set<Spot> dirConn, Set<Spot> visited, Spot from, Spot initial) {
- if (from.equals(initial)) {
- return true;
- }
- for (Spot s : dirConn) {
- if (!(visited.contains(s))) {
- return true;
- }
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement