我试图实现Dijkstras算法然而在它的某个地方,似乎我创造了一个无限循环,我不能找到我的生活。我首先将“城市”对象排序为一系列列表,然后尝试运行dijkstras算法以找到两个城市之间的最短路径。我知道要看很多,但我在这里遇到障碍。
排序功能
public static City[] store() throws FileNotFoundException{
File input = new File("input.txt");
Scanner in = new Scanner(input);
int numCities = in.nextInt();
if(numCities < 3 || numCities > 1000){
System.out.println("Incorrect input");
System.exit(-1);
}
City[] cities = new City[numCities + 1];
for(int i = 1; i < cities.length; i++){
cities[i] = new City(i);
}
int numRoads = in.nextInt();
if(numRoads < 2 || numRoads > 10000){
System.out.println("Incorrect input");
System.exit(-1);
}
int currCity = in.nextInt();
int count = 3;
while(count < cities.length){
cities[currCity].motelPrice = in.nextInt();
if(count < cities.length - 1)
currCity = in.nextInt();
count++;
}
while(in.hasNext()){
City activeCity;
currCity = in.nextInt();
int nextCity = in.nextInt();
int weight = in.nextInt();
if(cities[currCity].next == null){
cities[currCity].next = duplicate(cities, nextCity, weight);
addCity(cities, nextCity, duplicate(cities, currCity, weight));
}
else{
activeCity = cities[currCity];
while(activeCity.next != null){
activeCity = activeCity.next;
}
activeCity.next = duplicate(cities, nextCity, weight);
addCity(cities, nextCity, duplicate(cities, currCity, weight));
}
}
for( int k = 1; k < cities.length; k++){
System.out.print("["+k+" $"+cities[k].motelPrice+"]");
City activeCity = cities[k];
while(activeCity.next != null){
activeCity = activeCity.next;
System.out.print("($"+activeCity.nextWeight+")-->["+activeCity.cityIndex+"]");
}
System.out.println();
}
return cities;
}
迪杰斯特拉
public static int[] dijkstra(City[] cities, int source){
HashSet q = new HashSet();
for(int i = 1; i < cities.length; i++){
q.add(cities[i]);
}
int[] dist = new int[cities.length];
int[] prev = new int[cities.length];
for (int i=0; i<dist.length; i++) {
dist[i] = Integer.MAX_VALUE;
}
dist[source] = 0;
while(q.isEmpty() == false){
City u = new City(0);
int x;
int min = Integer.MAX_VALUE;
for(int j = 0; j < dist.length; j++){
if(dist[j] < min){
min = dist[j];
if(q.contains(cities[j])){
u = cities[j];
q.remove(u);
City v = u;
while(v.next != null){
v = v.next;
int alt = dist[u.cityIndex] + v.nextWeight;
if(alt < (dist[v.cityIndex])){
dist[v.cityIndex] = alt;
prev[v.cityIndex] = u.cityIndex;
}
}
}
}
}
}
return dist;
}