Beispiel #1
0
 private void recPaths(double maxCost, double currCost, City currCity) {
   // Backtrack if above max cost
   if (currCost > maxCost) {
     marked[currCity.id() - 1] = false;
     return;
   }
   // Print current path before continuing along routes
   if (edgeTo[currCity.id() - 1] != null) {
     System.out.printf("Cost: %.0f Path (reversed): ", currCost);
     City temp = currCity;
     for (Route r = edgeTo[temp.id() - 1]; r != null; r = edgeTo[temp.id() - 1]) {
       System.out.printf("%s %.0f ", temp, r.price());
       temp = r.other(temp);
     }
     System.out.println(temp);
   }
   // Recursion
   marked[currCity.id() - 1] = true;
   for (Route r : adj[currCity.id() - 1]) {
     City other = r.other(currCity);
     // Don't follow route if other city already in path
     if (!marked[other.id() - 1]) {
       edgeTo[other.id() - 1] = r;
       recPaths(maxCost, currCost + r.price(), other);
     }
   }
   // traversed all paths from currCity, backtrack to previous city
   marked[currCity.id() - 1] = false;
 }
Beispiel #2
0
 // relax edge e and update pq if changed
 private void relaxC(Route r, int v) {
   City city2 = r.other(cities[v]);
   int w = city2.id() - 1;
   if (costTo[w] > costTo[v] + r.price()) {
     costTo[w] = costTo[v] + r.price();
     edgeTo[w] = r;
     if (costPQ.contains(w)) costPQ.change(w, costTo[w]);
     else costPQ.insert(w, costTo[w]);
   }
 }
Beispiel #3
0
 // Option 4
 public void shortestByCost(String c1, String c2) {
   System.out.println("SHORTEST COST PATH from " + c1 + " to " + c2);
   System.out.println("--------------------------------------------------------");
   City city1 = null;
   City city2 = null;
   for (int i = 0; i < numCities; i++) {
     if (cities[i].name().equals(c1)) {
       city1 = cities[i];
     }
     if (cities[i].name().equals(c2)) {
       city2 = cities[i];
     }
   }
   if (c1.equals(c2) || city1 == null || city2 == null) {
     System.out.println("Invalid city choice(s)");
     return;
   }
   costTo = new double[numCities];
   edgeTo = new Route[numCities];
   for (int i = 0; i < numCities; i++) costTo[i] = Double.POSITIVE_INFINITY;
   costTo[city1.id() - 1] = 0;
   // relax vertices in order of distance from s
   costPQ = new IndexMinPQ<Double>(numCities);
   costPQ.insert(city1.id() - 1, costTo[city1.id() - 1]);
   while (!costPQ.isEmpty()) {
     int v = costPQ.delMin();
     for (Route r : adj[v]) relaxC(r, v);
   }
   if (costTo[city2.id() - 1] == Double.POSITIVE_INFINITY) {
     System.out.println("No path");
     return;
   }
   System.out.printf("Shortest cost from %s to %s is %.2f\n", c1, c2, costTo[city2.id() - 1]);
   System.out.println("Path with edges (in reverse order):");
   City currCity = city2;
   for (Route r = edgeTo[city2.id() - 1]; r != null; r = edgeTo[currCity.id() - 1]) {
     System.out.print(currCity + " " + r.price() + " ");
     currCity = r.other(currCity);
   }
   System.out.println(currCity);
 }