0
我學習最短路徑算法,和我想要實現的Dijkstra算法,需要從這樣的文件,輸入:Dijkstra算法無限循環
7
A
B
C
D
E
F
G
A B 21
A C 14
B E 5
B D 7
D F 3
E C 44
E G 53
E D 123
G F 51
問題是,當我添加額外的優勢像DB 12有些頂點,:
Dijkstra算法:
public Set<Vertex> dijkstraAlgo(Graph G, int s) {
initializeSingleSource(G, s);
Set<Vertex> set = new HashSet<Vertex>(); // intitially empty set of
// vertexes
Queue<Vertex> Q = new PriorityQueue<Vertex>(10, new VertexComparator()); // min
// priority
// queue
for (Vertex v : G.vertices) { // add source to priority queue
Q.add(G.vertices[s]);
}
while (Q.size() != 0) {
Vertex u = Q.poll(); // extract vertex which have min distance in
// priority queue
set.add(u); // add that vertex to set
for (String vertexId : u.neighbours.keySet()) { // see neighbours of
// vertex extracted
int vertexNum = indexForName(G, vertexId);
Vertex v = G.vertices[vertexNum];
int w = weightFunc(G, u, v);
relax(u, v, w);
Q.add(v);
}
}
return set;
}
讀取文件:
public class Graph {
Vertex[] vertices;
public Graph(String file) throws FileNotFoundException{
Scanner sc = new Scanner(new File(file));
vertices=new Vertex[sc.nextInt()];
for (int v = 0; v < vertices.length; v++){
vertices[v] = new Vertex(sc.next());
}
while (sc.hasNext()) {
int v1= indexForName(sc.next()); //read source vertex
String destination=sc.next(); //read destination vertex
int w=sc.nextInt(); //read weight of the edge
vertices[v1].neighbours.put(destination, w); //put the edge adjacent to source vertex
}
sc.close();
}
MAIN:
public static void main(String[] args) throws FileNotFoundException {
String fileName = "Dijikstra.txt";
Dijkstra dijkstra = new Dijkstra(fileName);
Set<Vertex> vertexInfo = dijkstra.dijkstraAlgo(dijkstra.graph, 0);
System.out
.println("Printing min distance of all vertexes from source vertex A ");
for (Vertex v : vertexInfo) {
System.out.println("Id: " + v.id + " distance: " + v.d + " Comming From " + v.p);
}
}
VERTEX:
class Vertex{
String id;
int d; //to store min distance from source
Vertex p; //to store last vertex from which min distance is reached
Map<String,Integer> neighbours; //to store edges of adjacent to the vertex
public Vertex(String id){
this.id=id;
neighbours=new HashMap<String,Integer>();
}
}
我只是用s的源頂點初始化它! 將它貼在上面。 謝謝 –