1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| class Vertex implements Comparable<Vertex>
{
public final String name;
public Edge[] adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex previous;
public Vertex(String argName) { name = argName; }
public String toString() { return name; }
public int compareTo(Vertex other)
{
return Double.compare(minDistance, other.minDistance);
}
}
/**Classe d'arc qu'on utilise dans la classe de Dijkstra**/
class Edge
{
public final Vertex target;
public final double weight;
public Edge(Vertex argTarget, double argWeight)
{ target = argTarget; weight = argWeight; }
}
/**Classe de Dijkstra utilise pour le calcul du chemin le plus court**/
class Dijkstra
{
// simple compute paths function
public static void computePaths(Vertex source)
{
source.minDistance = 0.0;
//Visit each vertex u, always visiting vertex with smallest minDistance first
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();
// Visit each edge exiting u
for (Edge e : u.adjacencies)
{
Vertex v = e.target;
double weight = e.weight;
//double distanceThroughU = u.minDistance + weight;
double weight2=0;if (weight!=0){weight2=1;}
//relax the edge (u,v)
double distanceThroughU = u.minDistance + weight2;
if (distanceThroughU < v.minDistance) {
//remove v from queue
vertexQueue.remove(v);
v.minDistance = distanceThroughU ;
v.previous = u;
//re-add v to queue
vertexQueue.add(v);
}
}
}
}
//get shortest path function
public static List<Vertex> getShortestPathTo(Vertex target)
{
List<Vertex> path = new ArrayList<Vertex>();
for (Vertex node = target; node != null; node = node.previous)
path.add(node);
Collections.reverse(path);
return path;
}
} |
Partager