/** * Initializes a new graph that is a deep copy of <tt>G</tt>. * * @param G the graph to copy */ public Graph(Graph G) { this(G.V()); this.E = G.E(); for (int v = 0; v < G.V(); v++) { // reverse so that adjacency list is in same order as original Stack<Integer> reverse = new Stack<Integer>(); for (int w : G.adj[v]) { reverse.push(w); } for (int w : reverse) { adj[v].add(w); } } }
/** * Returns a random simple graph containing <tt>V</tt> vertices and <tt>E</tt> edges. * * @param V the number of vertices * @param E the number of vertices * @return a random simple graph on <tt>V</tt> vertices, containing a total of <tt>E</tt> edges * @throws IllegalArgumentException if no such simple graph exists */ public static Graph simple(int V, int E) { if (E > (long) V * (V - 1) / 2) // 简单图不含自环和平行边 throw new IllegalArgumentException("Too many edges"); if (E < 0) throw new IllegalArgumentException("Too few edges"); Graph G = new Graph(V); SET<Edge> set = new SET<Edge>(); while (G.E() < E) { // 创建随机简单图 int v = StdRandom.uniform(V); int w = StdRandom.uniform(V); Edge e = new Edge(v, w); if ((v != w) && !set.contains(e)) { set.add(e); G.addEdge(v, w); } } return G; }
/** * Returns a random simple bipartite graph on <tt>V1</tt> and <tt>V2</tt> vertices with <tt>E</tt> * edges. * * @param V1 the number of vertices in one partition * @param V2 the number of vertices in the other partition * @param E the number of edges * @return a random simple bipartite graph on <tt>V1</tt> and <tt>V2</tt> vertices, containing a * total of <tt>E</tt> edges * @throws IllegalArgumentException if no such simple bipartite graph exists */ public static Graph bipartite(int V1, int V2, int E) { if (E > (long) V1 * V2) throw new IllegalArgumentException("Too many edges"); if (E < 0) throw new IllegalArgumentException("Too few edges"); Graph G = new Graph(V1 + V2); int[] vertices = new int[V1 + V2]; for (int i = 0; i < V1 + V2; i++) vertices[i] = i; StdRandom.shuffle(vertices); SET<Edge> set = new SET<Edge>(); while (G.E() < E) { int i = StdRandom.uniform(V1); int j = V1 + StdRandom.uniform(V2); Edge e = new Edge(vertices[i], vertices[j]); if (!set.contains(e)) { set.add(e); G.addEdge(vertices[i], vertices[j]); } } return G; }
public static int avgDegree(Graph G) { return 2 * G.E() / G.V(); }