package graphs.digraphs; import java.util.Set; import java.util.HashSet; /** * DiGraph class represents an directed graph of vertices named 0 through V-1. * Parallel edges and self-loops are permitted. */ public class DiGraph { private final int numV; private int numE; private Set<Integer>[] adjacents; /** * Create an empty digraph with V vertices. */ public DiGraph(int v) { if (v < 0) throw new RuntimeException("Number of vertices must be nonnegative"); this.numV = v; this.numE = 0; adjacents = (Set<Integer>[]) new Set[numV]; for (int i = 0; i < v; i++) { adjacents[i] = new HashSet<Integer>(); } } /** * Return the number of vertices in the digraph. */ public int numberOfVerteces() { return numV; } /** * Return the number of edges in the digraph. */ public int numberOfEdges() { return numE; } /** * Add the directed edge v-w to the digraph. */ public void addEdge(int v, int w) { adjacents[v].add(w); numE++; } /** * Return the list of neighbors of vertex v as in Iterable. */ public Iterable<Integer> adjacents(int v) { return adjacents[v]; } /** * Return a string representation of the digraph. */ public String toString() { StringBuilder s = new StringBuilder(); //String NEWLINE = System.getProperty("line.separator"); s.append(numV + " " + numE + "\n"); for (int i = 0; i < numV; i++) { s.append(i + ": "); for (int w : adjacents[i]) { s.append(w + " "); } s.append("\n"); } return s.toString(); } }