如何在图中表示双向边
How to represent bi-directional edges in graph
所以我正在使用 JGraphT 库,并且我已经有一个方法可以在我的程序中创建双向边。
然而,当我显示图表时,它目前显示 return 方向,如下所示:
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");
可能不是最好的代码:
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);
}
}
所以我正在使用 JGraphT 库,并且我已经有一个方法可以在我的程序中创建双向边。
然而,当我显示图表时,它目前显示 return 方向,如下所示:
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");
可能不是最好的代码:
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);
}
}