在java中的图实现 [英] Graphs implementation in java

查看:128
本文介绍了在java中的图实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试创建一个使用另一个类的Graph类,即Vertex类来表示图的所有顶点。我不确定是否需要一个表示两个顶点之间可能连接的Edge类,因为每个顶点都可以跟踪它所连接的其他节点。但我不确定这是否正确。你认为什么?



谢谢。 你不用不必使用 Edge 类。您可以使用邻接列表并仍然正确表示未加权图。对于加权图,您需要一种方法来表示边缘成本,因此使用 Edge 类是适当的。

  class Graph< E> {
私人列表< Vertex< E>>顶点;

private static class Vertex< E> {
E elem;
List< Vertex< E>>邻居;
}
}


I am trying to create a Graph class that uses another class, the Vertex class to represent all the vertices of the graph. I am not sure if I need an Edge class that will represent the possible connections between two vertices, because every vertex can keep track of the other nodes it is connected to. But I am not sure if this is correct. What do you think?

Thank you.

解决方案

You don't have to use an Edge class. You can use adjacency lists and still represent an unweighted graph correctly. For a weighted graph you need a way to represent edge costs, and thus using an Edge class would be appropriate.

class Graph<E> {
    private List<Vertex<E>> vertices;

    private static class Vertex<E> {
        E elem;
        List<Vertex<E>> neighbors;
    }
}

这篇关于在java中的图实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆