Graph

賈小強
转载请注明原创出处,谢谢!

package com.lab1.test4;

import java.util.HashSet;

import com.lab1.test1.LinkedBag;

public class Graph {
    private int E;
    private int V;
    private LinkedBag[] adj;

    public Graph(int[][] edges) {
        HashSet set = new HashSet<>();
        for (int i = 0; i < edges.length; i++) {
            set.add(edges[i][0]);
            set.add(edges[i][1]);
        }
        V = set.size();
        adj = new LinkedBag[V];
        for (int v = 0; v < V; v++) {
            adj[v] = new LinkedBag<>();
        }
        for (int i = 0; i < edges.length; i++) {
            int v = edges[i][0];
            int w = edges[i][1];
            addEdge(v, w);
            E++;
        }
    }

    private void addEdge(int v, int w) {
        adj[v].add(w);
        adj[w].add(v);
    }

    public Iterable adj(int v) {
        return adj[v];
    }

    public int E() {
        return E;
    }

    public int V() {
        return V;
    }

    public static void main(String[] args) {
        int[][] edges = { { 0, 5 }, { 4, 3 }, { 0, 1 }, { 9, 12 }, { 6, 4 }, { 5, 4 }, { 0, 2 }, { 11, 12 }, { 9, 10 },
                { 0, 6 }, { 7, 8 }, { 9, 11 }, { 5, 3 } };
        Graph graph = new Graph(edges);
        System.out.println("vertex : "+graph.V());
        System.out.println("edge   : "+graph.E());
        for (int v = 0; v < graph.V(); v++) {
            System.out.print(v + " : ");
            for (int w : graph.adj(v)) {
                System.out.print(w + " ");
            }
            System.out.println();
        }
    }

}

输出

vertex : 13
edge   : 13
0 : 6 2 1 5 
1 : 0 
2 : 0 
3 : 5 4 
4 : 5 6 3 
5 : 3 4 0 
6 : 0 4 
7 : 8 
8 : 7 
9 : 11 10 12 
10 : 9 
11 : 9 12 
12 : 11 9 

Happy learning !!

你可能感兴趣的:(Graph)