Java - Which is the best implementation structure for Graph?

前端 未结 8 2110
我在风中等你
我在风中等你 2021-02-02 16:47

The graph is very large but undirected. Edges are unweighted.

In my implementation, I have to find the vertex with max degree and do deletion on both vertexes and edges.

8条回答
  •  旧时难觅i
    2021-02-02 17:03

    My suggestion would be to store the vertexes in a priority queue. That way you can have very fast access to the vertex with the highest degree. As for how to implement the vertexes, I would store each neighboring vertex in some kind of set data-structure such as a HashSet or a TreeSet to be able to remove stuff efficiently. I wouldn't represent the edges explicitly, it's not needed.

    Code, something along the lines of:

    class Graph {
    
      PriorityQueue vertexes;
    
      public Graph() {
        vertexes = new PriorityQueue(10,new Vertex());
      }
    
      public Vertex maxDegreeVertex() {
        return vertexes.peek();
      }
    
      ...
    
    }
    
    class Vertex implements Comparator {
      HashSet edges;
    
      public Vertex() {
        edges = new HashSet();
      }
    
      public compare(Vertex v1, Vertex v2) {
        v2.edges.size().compareTo(v1.edges.size());
      }
    
      ...
    
    }
    

    Hope this helps.

提交回复
热议问题