public class Graph extends Object
Graph
class represents an undirected graph of vertices
named 0 through V – 1.
It supports the following two primary operations: add an edge to the graph,
iterate over all of the vertices adjacent to a vertex. It also provides
methods for returning the degree of a vertex, the number of vertices
V in the graph, and the number of edges E in the graph.
Parallel edges and selfloops are permitted.
By convention, a selfloop vv appears in the
adjacency list of v twice and contributes two to the degree
of v.
This implementation uses an adjacencylists representation, which
is a vertexindexed array of Bag
objects.
It uses Θ(E + V) space, where E is
the number of edges and V is the number of vertices.
All instance methods take Θ(1) time. (Though, iterating over
the vertices returned by adj(int)
takes time proportional
to the degree of the vertex.)
Constructing an empty graph with V vertices takes
Θ(V) time; constructing a graph with E edges
and V vertices takes Θ(E + V) time.
For additional documentation, see Section 4.1 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
Constructor and Description 

Graph(Graph G)
Initializes a new graph that is a deep copy of
G . 
Graph(In in)
Initializes a graph from the specified input stream.

Graph(int V)
Initializes an empty graph with
V vertices and 0 edges. 
Modifier and Type  Method and Description 

void 
addEdge(int v,
int w)
Adds the undirected edge vw to this graph.

Iterable<Integer> 
adj(int v)
Returns the vertices adjacent to vertex
v . 
int 
degree(int v)
Returns the degree of vertex
v . 
int 
E()
Returns the number of edges in this graph.

static void 
main(String[] args)
Unit tests the
Graph data type. 
String 
toString()
Returns a string representation of this graph.

int 
V()
Returns the number of vertices in this graph.

public Graph(int V)
V
vertices and 0 edges.
param V the number of verticesV
 number of verticesIllegalArgumentException
 if V < 0
public Graph(In in)
in
 the input streamIllegalArgumentException
 if in
is null
IllegalArgumentException
 if the endpoints of any edge are not in prescribed rangeIllegalArgumentException
 if the number of vertices or edges is negativeIllegalArgumentException
 if the input stream is in the wrong formatpublic Graph(Graph G)
G
.G
 the graph to copyIllegalArgumentException
 if G
is null
public int V()
public int E()
public void addEdge(int v, int w)
v
 one vertex in the edgew
 the other vertex in the edgeIllegalArgumentException
 unless both 0 <= v < V
and 0 <= w < V
public Iterable<Integer> adj(int v)
v
.v
 the vertexv
, as an iterableIllegalArgumentException
 unless 0 <= v < V
public int degree(int v)
v
.v
 the vertexv
IllegalArgumentException
 unless 0 <= v < V
public String toString()
public static void main(String[] args)
Graph
data type.args
 the commandline arguments