Java: how to represent graphs?

前端 未结 12 1489
感动是毒
感动是毒 2020-12-02 12:17

I\'m implementing some algorithms to teach myself about graphs and how to work with them. What would you recommend is the best way to do that in Java? I was thinking somethi

12条回答
  •  没有蜡笔的小新
    2020-12-02 12:54

    A simple representation written by 'Robert Sedgwick' and 'Kevin Wayne' is available at http://algs4.cs.princeton.edu/41graph/Graph.java.html

    Explanation copied from the above page.

    The Graph class represents an undirected graph of vertices named 0 through V - 1.

    It supports the following two primary operations: add an edge to the graph, iterate over all of the vertices adjacent to a vertex. It also provides methods for returning the number of vertices V and the number of edges E. Parallel edges and self-loops are permitted. By convention, a self-loop v-v appears in the adjacency list of v twice and contributes two to the degree of v.

    This implementation uses an adjacency-lists representation, which is a vertex-indexed array of Bag objects. All operations take constant time (in the worst case) except iterating over the vertices adjacent to a given vertex, which takes time proportional to the number of such vertices.

提交回复
热议问题