图的定义

图由顶点和边组成。

public class Graph {
    Set nodes = new HashSet();
    Set edges=new HashSet<>();

    public Graph(){
        
    }
    public Graph(Set nodes,Set edges){
        this.nodes=nodes;
        this.edges=edges;
    }
    class Node {
        int value;
        List edges = new LinkedList();

        public Node(int value) {
            this.value = value;
        }

        public void setEdges(Edge edge) {

            edges.add(edge);
        }
    }

    class Edge {
        Node start;
        Node end;
        int weight;

        public Edge(Node start, Node end,int weight) {
            this.start = start;
            this.end = end;
            this.weight = weight;
        }
    }

    public Node createNode(int value) {
        Node node = new Node(value);
        nodes.add(node);
        return node;
    }

    public Edge insertEdge(Node start, Node end) {
        if (nodes.contains(start) && nodes.contains(end)) {
            Edge edge = new Edge(start, end);
            start.setEdges(edge);
            end.setEdges(edge);
            edges.add(edge);
            return edge;
        }
        return null;
    }

    public void removeNode(Node node) {
        if (nodes.contains(node)) {
            node.edges = null;
            nodes.remove(node);
        }
    }

    public void removeEdge(Node start, Node end) {
        List edges = start.edges;
        for (Edge e : edges) {
            Node endNode = e.end;
            if (endNode.equals(end)) {
                edges.remove(e);
            }
        }

        List edgesEnd = end.edges;
        for (Edge e : edgesEnd) {
            Node endNode = e.end;
            if (endNode.equals(start)) {
                edgesEnd.remove(e);
                edges.remove(e);

            }
        }
    }

}

你可能感兴趣的:(图的定义)