コード例 #1
0
 public int compare(Station arg0, Station arg1) {
   if (arg0.getDistanceFromSource() > arg1.getDistanceFromSource()) {
     return 1;
   } else {
     return -1;
   }
 }
コード例 #2
0
 private void relax(Station station) {
   for (Station neighbor : station.getDestinations()) {
     if (!visited.contains(neighbor)) {
       int currentKnownDistance = getCurrentKnownDistance(station, neighbor);
       if (neighbor.getDistanceFromSource() > currentKnownDistance) {
         neighbor.setDistanceFromSource(currentKnownDistance);
         unvisited.add(neighbor);
       }
     }
   }
 }
コード例 #3
0
 private void relaxRoundTrip(Station station, Station destination) {
   for (Station neighbor : station.getDestinations()) {
     if (!visited.contains(neighbor)) {
       int currentKnownDistance = getCurrentKnownDistance(station, neighbor);
       // to allow round trip if the neighbor is the destination, add
       // it back to the queue
       if (neighbor.getDistanceFromSource() > currentKnownDistance
           || neighbor.equals(destination)) {
         neighbor.setDistanceFromSource(currentKnownDistance);
         unvisited.add(neighbor);
       }
     }
   }
 }
コード例 #4
0
  public int findShortestTrip(Station from, Station to) {
    initialize();
    unvisited.add(from);
    from.setDistanceFromSource(0);

    while (!unvisited.isEmpty()) {
      Station closest = unvisited.poll();
      if (closest.equals(to)) {
        return closest.getDistanceFromSource();
      }
      visited.add(closest);
      relax(closest);
    }
    throw new MissingRouteException("Missing connection: " + from + " - " + to);
  }
コード例 #5
0
  public int findShortestRoundTrip(Station from) {
    initialize();
    unvisited.add(from);
    from.setDistanceFromSource(0);
    // to allow round trip, for the first iteration skip 'are we there yet'
    // check and don't add station to visited
    boolean start = true;

    while (!unvisited.isEmpty()) {
      Station closest = unvisited.poll();
      if (!start && closest.equals(from)) {
        return closest.getDistanceFromSource();
      }
      if (!start) {
        visited.add(closest);
      }
      relaxRoundTrip(closest, from);
      start = false;
    }
    throw new MissingRouteException("Missing round connection: " + from);
  }
コード例 #6
0
 private void initializeDistances() {
   for (Station station : stations) {
     station.setDistanceFromSource(Integer.MAX_VALUE);
   }
 }
コード例 #7
0
 private int getCurrentKnownDistance(Station current, Station neighbor) {
   return current.getDistanceFromSource() + current.getDistanceTo(neighbor.getId());
 }