Java - Which is the best implementation structure for Graph?

前端 未结 8 2089
我在风中等你
我在风中等你 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
    闹比i (楼主)
    2021-02-02 17:23

        public class Graph {
        private Setvertices;
        private Setedges;
        private Map>adj;
        // Getter setter
    
    
    
        public Graph(Set vertices, Set edges, Map> adj) {
            super();
            this.vertices = vertices;
            this.edges = edges;
            this.adj = adj;
        }
    }
    
    // Vertex class
    public class Vertex {
        private String name;
    
        public Vertex(String name) {
            super();
            this.name = name;
        }
    
    
    }
    
    // Edge class 
    
    public class Edge {
        private Vertex from;
        private Vertex to;
        private int weight;
    
        public Edge(Vertex from, Vertex to,int weight) {
            super();
            this.from = from;
            this.to = to;
            this.weight = weight;
        }
    
    
    }
    
    // Driver class 
    
    import java.util.HashSet;
    import java.util.Set;
    
    public class Test {
        public static void  main(String[]args) {
            Graph gr = new Graph();
            Vertex a = new Vertex("a");
            Vertex b = new Vertex("b");
            Vertex c = new Vertex("c");
            Vertex d = new Vertex("d");
            Vertex e = new Vertex("e");
            Vertex f = new Vertex("f");
            Vertex g = new Vertex("g");
    
    
            Setvertices = gr.getVertices();
            if(vertices == null){
                vertices  = new HashSet<>();
                vertices.add(a);
                vertices.add(b);
                vertices.add(c);
                vertices.add(d);
                vertices.add(e);
                vertices.add(f);
                vertices.add(g);
            }
    
            Edge ae = new Edge(a, e, 3);        
            Edge ac = new Edge(a, c, 1);
            Edge cf = new Edge(c, f, 9);
            Edge cd = new Edge(c, d, 4);
            Edge eb = new Edge(e, b, 2);
            Edge bd = new Edge(b, d, 5);
            Edge df = new Edge(d, f, 7);
    
        Setedges = gr.getEdges();
        if(edges == null){
            edges = new HashSet();
            edges.add(ae);
            edges.add(ac);
            edges.add(cf);
            edges.add(cd);
            edges.add(eb);
            edges.add(bd);
            edges.add(bd);
        }
            gr.setVertices(vertices);
            gr.setEdges(edges);
    
        }
    
    }
    

提交回复
热议问题