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.
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.
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:
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:
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
, e.g. to return price
:
@Override
protected double getWeight() {
return price;
}
Otherwise, you will use the default edge weight, which is 1.0
.