Exemple #1
0
  public DijkstraGraph(List<Road> roads) {
    super();

    for (Road r : roads) {
      for (int i = 0; i < r.getNodes().length; i++) {
        Node n = r.getNodes()[i];
        DijkstraVertex neighbor = get(n);
        if (neighbor == null) {
          neighbor = new DijkstraVertex(n);
          put(n, neighbor);
        }
        if (i > 0) {
          neighbor.addVoisin(r.getNodes()[i - 1]);
        }
        if (i < r.getNodes().length - 1) {
          neighbor.addVoisin(r.getNodes()[i + 1]);
        }
      }
    }
  }
Exemple #2
0
  public List<Node> dijkstra(Building src, Building dest) {
    PriorityQueue<DijkstraVertex> aVisiter = new PriorityQueue<DijkstraVertex>();

    for (Node n : src.getNeighbors()) {
      DijkstraVertex source = (DijkstraVertex) get(n);
      aVisiter.add(source);
      source.distance = 0;
    }

    DijkstraVertex actuel = aVisiter.poll();
    int cpt = 0;
    while (!estUnVoisin(actuel.node, dest) && aVisiter.size() > 0) {
      cpt++;
      actuel.visited = true;
      for (Node n : actuel.neighbors) {
        int dist = actuel.distance + 1;
        DijkstraVertex tmp = (DijkstraVertex) get(n);
        if (dist < tmp.distance) {
          tmp.distance = dist;
          tmp.previous = actuel;
          if (!tmp.visited) {
            aVisiter.add(tmp);
          }
        }
      }
      actuel = aVisiter.poll();
    }

    System.out.println("Itérations: " + cpt);
    DijkstraVertex finalNode = null;
    for (Node n : dest.getNeighbors()) {
      actuel = (DijkstraVertex) get(n);
      if (finalNode == null) finalNode = actuel;
      if (actuel.distance < finalNode.distance) finalNode = actuel;
    }
    System.out.println(finalNode.distance);

    LinkedList<Node> res = new LinkedList<Node>();
    while (finalNode != null) {
      res.addFirst(finalNode.node);
      finalNode = finalNode.previous;
    }
    return res;
  }