简体   繁体   English

Dijkstra的最短路径算法不会返回权重最小的最短路径

[英]Dijkstra's Shortest Path algorithm not returning shortest path with smallest weight

I'm using a graph library called JGraphT and in my program I have several vertex's connected together by an edge with a weight of the cost of travel. 我正在使用一个名为JGraphT的图形库,在我的程序中,我通过一个边将几个顶点连接在一起,而这又增加了旅行成本。

In one example where i weight by just an integer, it works! 在我仅加权整数的一个示例中,它起作用了! But when i change this to using my class FlightData as the weight, it doesn't work. 但是,当我将其更改为使用我的类FlightData作为权重时,它不起作用。

Here is my code with the weight as just an integer: 这是我的代码,权重仅为整数:

List<DefaultWeightedEdge> path = DijkstraShortestPath.findPathBetween(graph, start, end);
    for(int i = 0; i < path.size(); i++) {
        DefaultWeightedEdge edge = path.get(i);
        System.out.println((i+1) + " " + graph.getEdgeSource(edge) + " -> " + graph.getEdgeTarget(edge));
    }

Here is my code for the weight as my FlightData class: 这是我作为FlightData类的重量代码:

List<FlightData> path = DijkstraShortestPath.findPathBetween(graph, start, end);    
for(int i = 0; i < path.size(); i++) {
        FlightData f = path.get(i);
    System.out.println((i+1) + " " + graph.getEdgeSource(f) + " -> " + graph.getEdgeTarget(f));
}

My FlightData class is simply just a class with accessor methods: 我的FlightData类只是具有访问器方法的类:

import org.jgrapht.graph.DefaultWeightedEdge;

public class FlightData extends DefaultWeightedEdge
{
    private String flightNumber, depTime, arrTime;
    private double price;

    public FlightData(String flightNumber, String depTime,
            String arrTime, double price) {
        this.flightNumber = flightNumber;
        this.depTime = depTime;
        this.arrTime = arrTime;
        this.price = price;
    }

    public String getFlightNumber() {
        return flightNumber;
    }
    public String getDepartureTime() {
        return depTime;
    }
    public String getArrivalTime() {
        return arrTime;
    }
    public double getFlightPrice() {
        return price;
    }
}

Can anyone point me in the right direction as to why one reveals the shortest path with the lowest weight and the other with the shortest path and not necessarily the lowest weight? 谁能为我指出正确的方向,为什么一个人显示出权重最低的最短路径,而另一个人则显示出权重最低且不一定是最低的路径? (If there is a direct path between two vertexes it will just return that!) (如果两个顶点之间存在直接路径,它将返回该路径!)

You need to override DefaultWeightedEdge.getWeight() in FlightData , eg to return price : 您需要在FlightData覆盖DefaultWeightedEdge.getWeight() ,例如,要返回price

@Override
protected double getWeight() {
  return price;
}

Otherwise, you will use the default edge weight, which is 1.0 . 否则,您将使用默认的边缘权重1.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM