I am new to Graph theory in addition to this JGraphT (Java) library I'm using in order to implement a solution to a logistics issue I'm trying to solve. As such, I'm a little lost on the best way to tackle this problem I'm having to represent a shipment's path from Point A to Point C given the incoming data.
Given a list of Conveyance segments or Ordered Pairs, how do I represent this programmatically with the fewest possible edges?
Delivery 1
goes from Atlanta to Mumbai.
Delivery 2
goes from Atlanta to London.
Delivery 3
goes from London to Mumbai.
In my visual graph representation, I want to remove the explicit Atlanta to Mumbai
edge and simply infer that from the other edges and represent it simply as:
Atlanta -> London -> Mumbai
I feel like there's likely an existing Path Algorithm that can be applied to solve this rather simple use case but I'm struggling to figure out which one given my relative newness to the subject matter. If my requirement was to remove excessive vertices rather than edges, then it seems like the ShortestPathAlgorithm
would be of use here.
I can possibly identify the ultimate source
and sink
of my given pairs (i.e. Atlanta is the source and Mumbai is the sink) but don't want to go down the path of manually removing the edges if possible.
Current representation:
Desired representation:
I have created a class to get me close to implement the alternative Depth-first solution @JorisKinable mentions below but still not understanding why "Atlanta, Mumbai, and London" are listed in that order. If no weight is applied to the edges, what causes Mumbai to come before London in this scenario?
public final class Demo {
public static void main(String[] args) throws Exception {
// Create the graph object
Graph<String, DefaultEdge> graph = new DefaultDirectedGraph<>(DefaultEdge.class);
String atlanta = "Atlanta";
String london = "London";
String mumbai = "Mumbai";
graph.addVertex(atlanta);
graph.addVertex(london);
graph.addVertex(mumbai);
graph.addEdge(atlanta, london);
graph.addEdge(london, mumbai);
graph.addEdge(atlanta, mumbai);
ComponentNameProvider<String> vertexIdProvider = name -> name;
ComponentNameProvider<String> vertexLabelProvider = name -> name;
String start = graph.vertexSet().stream().filter(r -> r.equals("Atlanta")).findAny().get();
System.out.println("-- traverseGraph output");
traverseGraph(graph, start);
GraphExporter<String, DefaultEdge> exporter = new DOTExporter<>(vertexIdProvider, vertexLabelProvider, null);
Writer writer = new StringWriter();
exporter.exportGraph(graph, writer);
System.out.println(writer.toString());
}
private static void traverseGraph(Graph<String, DefaultEdge> graph, String start) {
Iterator<String> iterator = new DepthFirstIterator<>(graph, start);
while (iterator.hasNext()) {
String string = iterator.next();
System.out.println(string);
}
}
}