0

我正在使用 DefaultDirectedGraph 创建我的有向图,其中每个顶点都是一个对象。

DefaultDirectedGraph g = new DefaultDirectedGraph(DefaultEdge.class);

我想知道是否可以表征边缘?例如,我想保留学生之间的友谊信息。

或者我应该在边缘和友谊对象之间有一张地图?

4

1 回答 1

1

您当然可以在边缘存储信息。这是我最近自己使用的一个用例:

public class Intersection{
    public final long latitude;
    public final long longitude;
    public Intersection(long latitude, long longitude){ ...}
}

public class Street extends DefaultWeightedEdge{
    public final String streetName;
    public final int speedLimit;
    public final Street(...){...}
}

public class RoadNetwork{
    public final Graph<Intersection, Street> network=new DefaultDirectedGraph<>(Street.class);
    Intersection i1=new Intersection(..);
    Intersection i2=new Intersection(..);
    Street s=new Street(..);

    //Network with 1 street
    network.addVertex(i1);
    network.addVertex(i2);
    network.addEdge(i1,i2,s);
}

笔记:

  1. Street 扩展 DefaultWeightedEdge:在最新版本的 jgrapht 中不再需要扩展 DefaultEdge 或 DefaultWeightedEdge
  2. 在 jgrapht 中,所有的边都是对象。上例中使用自定义对象(如 Street)时,只能使用 addEdge(vertex1, vertex2, edgeObject) 方法。除非您向图形构造函数提供 EdgeFactory,否则您不能使用 addEdge(vertex1,vertex2) 方法。
  3. 一个常见的错误是将图形信息存储在边上。例如,将源路口和目标路口(街道的两个端点)存储在街道对象本身上是错误的。此信息存储在图表中。
  4. 在实现自己的顶点或边类时,必须实现 equals 和 hashCode 方法。有关详细信息,请参阅https://github.com/jgrapht/jgrapht/wiki/Users:-EqualsAndHashCode
于 2018-03-19T21:12:05.970 回答