所以我正在使用JGraphT库,我已经有了一个方法来在我的程序中创建双向边。
然而,当我显示图形时,它当前显示返回方向,如下所示:
D1 -> D2
D2 -> D1
我希望它如下:
D1 <-> D2
以下是我目前使用的代码:
for(String vertex : destinations) {
Set<DefaultWeightedEdge> edges = graph.outgoingEdgesOf(vertex);
for(DefaultWeightedEdge edge : edges) {
System.out.println(graph.getEdgeSource(edge) + " -> " + graph.getEdgeTarget(edge));
}
}
作为参考,这是我使用的目的地列表:
ArrayList<String> destinations = new ArrayList<String>();
destinations.add("Amsterdam");
destinations.add("Boston");
destinations.add("Chicago");
destinations.add("Edinburgh");
destinations.add("Heathrow");
destinations.add("Hong Kong");
destinations.add("Montreal");
destinations.add("New Delhi");
destinations.add("Shanghai");
destinations.add("Toronto");
答案 0 :(得分:1)
可能不是最好的代码:
for (String source: destinations) {
Set<DefaultWeightedEdge> edges = graph.outgoingEdgesOf(source);
for (DefaultWeightedEdge edge : edges) {
//String source = graph.getEdgeSource(edge);
String target = graph.getEdgeTarget(edge);
boolean comingBack = graph.containsEdge(target, source);
if (comingBack && source.compareTo(target) > 0) {
continue; // Skip B <-> A as already A <-> B.
}
String arrow = comingBack ? "<->" : "->";
System.out.printf("%s %s %s%n", source, arrow, target);
}
}