示例#1
0
 // 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);
 }