``` 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 099 100 101 102 103 104 105 106 107 108 109 110 111 112 ``` ```package algs41; import stdlib.*; import java.util.Iterator; import java.util.NoSuchElementException; /* *********************************************************************** * Compilation: javac AdjMatrixGraph.java * Execution: java AdjMatrixGraph V E * Dependencies: StdOut.java * * A graph, implemented using an adjacency matrix. * Parallel edges are disallowed; self-loops are allowd. * *************************************************************************/ public class XAdjMatrixGraph { private final int V; private int E; private final boolean[][] adj; // empty graph with V vertices public XAdjMatrixGraph(int V) { if (V < 0) throw new Error("Number of vertices must be nonnegative"); this.V = V; this.E = 0; this.adj = new boolean[V][V]; } // random graph with V vertices and E edges public XAdjMatrixGraph(int V, int E) { this(V); if (E < 0) throw new Error("Number of edges must be nonnegative"); if (E > V*(V-1) + V) throw new Error("Too many edges"); // can be inefficient while (this.E != E) { int v = (int) (V * Math.random()); int w = (int) (V * Math.random()); addEdge(v, w); } } // number of vertices and edges public int V() { return V; } public int E() { return E; } // add undirected edge v-w public void addEdge(int v, int w) { if (!adj[v][w]) E++; adj[v][w] = true; adj[w][v] = true; } // does the graph contain the edge v-w? public boolean contains(int v, int w) { return adj[v][w]; } // return list of neighbors of v public Iterable adj(int v) { return new AdjIterator(v); } // support iteration over graph vertices private class AdjIterator implements Iterator, Iterable { int v, w = 0; AdjIterator(int v) { this.v = v; } public Iterator iterator() { return this; } public boolean hasNext() { while (w < V) { if (adj[v][w]) return true; w++; } return false; } public Integer next() { if (hasNext()) { return w++; } else { throw new NoSuchElementException(); } } public void remove() { throw new UnsupportedOperationException(); } } // string representation of Graph - takes quadratic time public String toString() { String NEWLINE = System.getProperty("line.separator"); StringBuilder s = new StringBuilder(); s.append(V + " " + E + NEWLINE); for (int v = 0; v < V; v++) { s.append(v + ": "); for (int w : adj(v)) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } // test client public static void main(String[] args) { int V = Integer.parseInt(args[0]); int E = Integer.parseInt(args[1]); XAdjMatrixGraph G = new XAdjMatrixGraph(V, E); StdOut.println(G); } } ```