优先队列的最短路径问题

时间:2019-05-18 06:10:52

标签: java shortest

我创建了一个程序,试图找到纽约市火车站之间的最短路径。我有一个使用优先级队列的最短路径算法,但由于某种原因,我的队列无法正常工作。 autoAssLinks函数是为我的哈希集创建链接的功能。那是我认为唯一可能有问题的地方。

public void autoAddLinks() {

    InputReader input = new InputReader("StationsModified2.txt");
    new Graph();
    String currentLine = "";
    String stationPrev = "";
    String stationCurr = "";
    String inputLine = input.readLine();
    while (inputLine != null) { 
      if (inputLine.trim().equals("")) { //line is empty
        inputLine = input.readLine(); //reads next line
        continue; //ignore empty line

      } else {
        if (stationCurr.equals("")) { //first station of the line
          stationCurr = inputLine.trim();
        } else { //already have a station stored
          stationPrev = stationCurr;
          stationCurr = inputLine.trim();
          addLink(stationPrev, stationCurr, currentLine);
          addStation(stationCurr);
        }
      }
      inputLine = input.readLine();

    }

  }
public void path(Station a, Station b){
    q = new PriorityQueue();
    visited = new HashMap();
    Label from = new Label(a);
    from.cost = 0;
    q.add(from);
    for(Station station: g.stations.values()){
        if(!a.equals(station)){
            from = new Label(station);
            q.add(from);
        }
    }
    while(!q.isEmpty()){
        Label u = q.poll();
        visited.put(u.here.name, u);
        for(Link link: g.links){
            Label v = getLabel(link.from);
            if(link.from.equals(u.here.name)&& v != null){
                int newCost = u.cost + link.weight;
                if(newCost<v.cost){
                    v.cost = newCost;
                    v.from = u;
                    q.remove(v);
                    q.add(v);
                }
            }
        }
    }
    Label label = visited.get(b.name);
    route = new ArrayList();
    while(!label.here.equals(a)){
        route.add(label.here);
        label = label.from;
    }
    route.add(a);

    Collections.reverse(route);
    for(int i =0;i<route.size();i++){
        System.out.println(route.get(i).name);
    }
    }

0 个答案:

没有答案
相关问题