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; }
// Option 6 public void pathsUnderCost(double maxCost) { System.out.printf("ALL PATHS OF COST %.0f OR LESS\n", maxCost); System.out.println( "Note that routes are duplicated," + " once from each end city's point of view"); System.out.println( "--------------------------------" + "-----------------------------------------"); // find all paths starting at each city for (int i = 0; i < numCities; i++) { edgeTo = new Route[numCities]; // reset for each start city marked = new boolean[numCities]; recPaths(maxCost, 0, cities[i]); } }