Advertisement
Guest User

Untitled

a guest
Nov 18th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. /**
  2. * Returns the path between two cities with the minimum cost
  3. *
  4. * @param from the departing city
  5. * @param to the destination city
  6. * @return path
  7. */
  8. public LinkedList<Spot> minimumCost(Spot from, Spot to) {
  9. Spot initial = from;
  10. LinkedList<Spot> path = new LinkedList<>();
  11. path.add(from);
  12. Set<Spot> visited = new HashSet<>();
  13. visited.add(from);
  14. Spot add = new Spot();
  15. int aux, cost;
  16. while (!(from.equals(to))) {
  17. aux = 0;
  18. if (((Set) map.directConnections(from)).contains(to)) {
  19. path.add(to);
  20. from = to;
  21. }
  22. if (!(from.equals(to))) {
  23. if (verIfAllVisitedOrNoConnections(((Set) map.directConnections(from)), visited, from, initial)) {
  24. for (Spot s : map.directConnections(from)) {
  25. if (!(visited.contains(s))) {
  26. cost = map.getEdge(from, s).getCost();
  27. if (aux == 0) {
  28. aux = cost;
  29. add = s;
  30. }
  31. if (cost < aux) {
  32. aux = cost;
  33. add = s;
  34. }
  35. }
  36. }
  37. path.add(add);
  38. visited.add(add);
  39. from = add;
  40. } else {
  41. visited.add(from);
  42. path.remove(from);
  43. from = initial;
  44. }
  45. }
  46. }
  47. return path;
  48. }
  49.  
  50. private boolean verIfAllVisitedOrNoConnections(Set<Spot> dirConn, Set<Spot> visited, Spot from, Spot initial) {
  51. if (from.equals(initial)) {
  52. return true;
  53. }
  54. for (Spot s : dirConn) {
  55. if (!(visited.contains(s))) {
  56. return true;
  57. }
  58. }
  59. return false;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement