// Option 5 public void shortestByHops(String c1, String c2) { System.out.println("FEWEST HOPS 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; } marked = new boolean[numCities]; distTo = new int[numCities]; edgeTo = new Route[numCities]; for (int i = 0; i < numCities; i++) distTo[i] = Integer.MAX_VALUE; bfs(city1.id() - 1); if (distTo[city2.id() - 1] == Integer.MAX_VALUE) { System.out.println("No path"); return; } System.out.printf("Fewest hops from %s to %s is %d\n", c1, c2, distTo[city2.id() - 1]); City currCity = city2; for (Route r = edgeTo[city2.id() - 1]; r != null; r = edgeTo[currCity.id() - 1]) { System.out.print(currCity + " "); currCity = r.other(currCity); } System.out.println(currCity); }
// Option 10 public void removeCity(String c) { City city = null; for (int i = 0; i < numCities; i++) { if (cities[i].name().equals(c)) { city = cities[i]; } } if (city == null) { System.out.println("Invalid city choice"); return; } // Remove all routes connected to the city for (Route r : adj[city.id() - 1]) { City other = r.other(city); adj[other.id() - 1].remove(r); routes.remove(r); numRoutes--; } cities[city.id() - 1] = null; adj[city.id() - 1] = null; numCities--; // Shift and resize arrays as necessary shiftCities(city.id() - 1); shiftAdj(city.id() - 1); if (numCities < cities.length / 2) { // halve the lengths of the arrays resizeCities(cities.length / 2); resizeAdj(cities.length / 2); } }
// 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]); } }
private void relaxD(Route r, int v) { // relax edge e and update pq if changed City city2 = r.other(cities[v]); int w = city2.id() - 1; if (distTo[w] > distTo[v] + r.distance()) { distTo[w] = distTo[v] + r.distance(); edgeTo[w] = r; if (pq.contains(w)) pq.change(w, distTo[w]); else pq.insert(w, distTo[w]); } }
// Option 1 public void showAllRoutes() { System.out.println("SHOWING ALL DIRECT ROUTES"); System.out.println( "Note that routes are duplicated," + " once from each end city's point of view"); System.out.println( "--------------------------------" + "-----------------------------------------"); Object[] objArr = routes.toArray(); for (int i = 0; i < numRoutes; i++) { Route route = (Route) objArr[i]; System.out.println(route.toStringWN()); } }
public void removeRoute(City city1, City city2) { Route route = null; for (Route r : adj[city1.id() - 1]) { if (r.other(city1).equals(city2)) { route = r; break; } } adj[city1.id() - 1].remove(route); adj[city2.id() - 1].remove(route); routes.remove(route); numRoutes--; }
private void prim(int s, StringBuilder sb) { distTo[s] = 0; pq.insert(s, distTo[s]); while (!pq.isEmpty()) { int v = pq.delMin(); if (v != s) { Route r = edgeTo[v]; String str = String.format("%s, %s : %d\n", r.fst(), r.snd(), r.distance()); sb.append(str); } scan(v); } }
public static void main(String args[]) throws IOException { NetworkVersion nv = new NetworkVersion(2, ""); System.out.println("Solution#1"); nv.searchLines(); System.out.println("Solution#2"); for (int i = 0; i < nv.getLines().size(); i++) { nv.getLines().get(i).searchRoutes(); } System.out.println("Solution#3"); Route r = new Route(2, 1, 1); r.getStopAreas().get(0).searchStopPoints(); }
public void bfs(int s) { Queue<Integer> q = new Queue<Integer>(); distTo[s] = 0; marked[s] = true; q.enqueue(s); while (!q.isEmpty()) { int v = q.dequeue(); for (Route r : adj[v]) { int w = r.other(cities[v]).id() - 1; // index of other city on route if (!marked[w]) { edgeTo[w] = r; distTo[w] = distTo[v] + 1; marked[w] = true; q.enqueue(w); } } } }
private void scan(int v) { marked[v] = true; for (Route r : adj[v]) { int w = r.other(cities[v]).id() - 1; // index of other city in route if (marked[w]) { continue; // v-w is obsolete edge } if (r.distance() < distTo[w]) { distTo[w] = r.distance(); edgeTo[w] = r; if (pq.contains(w)) { pq.change(w, distTo[w]); } else { pq.insert(w, distTo[w]); } } } }
// 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); }
// Option 3 public void shortestByDistance(String c1, String c2) { System.out.println("SHORTEST DISTANCE 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; } distTo = new int[numCities]; edgeTo = new Route[numCities]; for (int i = 0; i < numCities; i++) distTo[i] = Integer.MAX_VALUE; distTo[city1.id() - 1] = 0; // relax vertices in order of distance from s pq = new IndexMinPQ<Integer>(numCities); pq.insert(city1.id() - 1, distTo[city1.id() - 1]); while (!pq.isEmpty()) { int v = pq.delMin(); for (Route r : adj[v]) relaxD(r, v); } if (distTo[city2.id() - 1] == Integer.MAX_VALUE) { System.out.println("No path"); return; } System.out.printf("Shortest distance from %s to %s is %d\n", c1, c2, distTo[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.distance() + " "); currCity = r.other(currCity); } System.out.println(currCity); }
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; }
public void run() { if (!star) { System.out.println( "Run PCC de " + zoneOrigine + ":" + origine + " vers " + zoneDestination + ":" + destination); } if (star) { System.out.println( "Run PCC-Star de " + zoneOrigine + ":" + origine + " vers " + zoneDestination + ":" + destination); } // decision temps ou distance. Si on est en mode covoiturage, ce n'est pas nécessaire car on est // forcément en temps if (covoit == 0) { Scanner sc = new Scanner(System.in); System.out.println("En temps(0) ou distance(1)?"); if (sc.nextInt() == 1) { this.setdist(true); } } // chronometrage long start_time = System.currentTimeMillis(); Label l = new Label(false, 0.0, null, this.graphe.sommets.get(origine)); chem.add(l); tas.insert(l); maplabel.put(this.graphe.sommets.get(origine), l); // affichage de l'origine et de la destination this.graphe.getDessin().setColor(Color.BLUE); this.graphe .getDessin() .drawPoint( this.graphe.sommets.get(origine).getlon(), this.graphe.sommets.get(origine).getlat(), 10); this.graphe .getDessin() .drawPoint( this.graphe.sommets.get(destination).getlon(), this.graphe.sommets.get(destination).getlat(), 10); // compteur d'elements explores int nb_explor = 0; int tas_max = 0; while (!(tas.isEmpty())) { // extraction du minimum Label pere = tas.findMin(); tas.deleteMin(); // on arrete le programme une fois la destination trouvee, sauf si l'on ne souhaite pas // arreter ---> covoiturage if (pere.getCourant().getNum() == destination && (covoit == 0)) { System.out.println("Algorithme termine!"); break; } pere.setMarquage(true); chem.add(pere); for (Route route : pere.getCourant().routes) { Sommet suiv = route.getArrivee(); // affichage du parcours en temps reel. On ne le fait pas dans l'optimisation de covoiturage // car cela surcharge trop le dessin. if (this.getcovoit() == 0) { this.graphe.getDessin().setColor(Color.gray); this.graphe .getDessin() .drawLine( suiv.getlon(), suiv.getlat(), pere.getCourant().getlon(), pere.getCourant().getlat()); } // declarations des variables de cout, cout secondaire et estimation double new_cout = 0.0; double estim = 0.0; // ESTIMATION VERY IMPORTANT double cout_sec = 0.0; if (this.dist_temps) // Cout n distance { double vitesse = ((double) (route.getDesc().vitesseMax())); new_cout = pere.getCout() + ((double) (route.getDist())); // cout secondaire, ici en temps cout_sec = pere.getCoutSec() + (60.0 * ((double) (route.getDist())) / (1000.0 * vitesse)); if (this.star) { estim = suiv.dist_vol_oiseau(this.graphe.sommets.get(destination)); } } else { // Cout en temps double vitesse = ((double) (route.getDesc().vitesseMax())); // cas du pieton if (this.getcovoit() == 1 && (vitesse == 130.0 || vitesse == 110.0)) { // ici, le pieton ne peut pas acceder a cette route, // elle est reservee aux voitures, le cout est donc le plus grand possible new_cout = Double.MAX_VALUE; } else { if (this.getcovoit() == 1) { vitesse = 4.0; } new_cout = pere.getCout() + (60.0 * ((double) (route.getDist())) / (1000.0 * vitesse)); // cout secondaire, ici en distance cout_sec = pere.getCoutSec() + ((double) (route.getDist())); } // Ici on modifie le calcul de l'estimation dans le cas d'un calcul Astar. VERY IMPORTANT if (this.star) { estim = suiv.cout_vol_oiseau(this.graphe.sommets.get(destination), this.graphe.getvitmax()); } } // on regarde si le sommet a deja un label associe avec un cout different de l'infini) // pour ce faire, on verifie juste qu'il est integre a la hashmap ou pas if (maplabel.containsKey(suiv)) { maplabel.get(suiv).setEstim(estim); // maj du label, et de la hashmap // on ne verifie pas si le sommet est marque : en effet, s'il l'est, son cout // est deja minimal et la condition suivante sera toujours fausse. if (maplabel.get(suiv).getCout() > new_cout) { maplabel.get(suiv).setCout(new_cout); maplabel.get(suiv).setPere(pere.getCourant()); maplabel.get(suiv).setCoutSec(cout_sec); tas.update(maplabel.get(suiv)); } } else { // le sommet a un cout infini : on cree un label, et on l'integre a la hashmap Label lab = new Label(false, new_cout, pere.getCourant(), suiv); lab.setEstim(estim); lab.setCoutSec(cout_sec); tas.insert(lab); maplabel.put(suiv, lab); // compteurs de performance nb_explor++; if (tas.size() > tas_max) { tas_max = tas.size(); } } } } // on affiche le chemin this.print_chemin(this.graphe.sommets.get(destination)); // fin du chronometre long end_time = System.currentTimeMillis(); long difference = end_time - start_time; // on affiche les performances System.out.println("Temps écoulé en millisecondes : " + difference); System.out.println("Elements explorés : " + nb_explor); System.out.println("Taille max du tas : " + tas_max); }