 • Print

## A Graph Structure

Listing 1 illustrates an excerpt from a Java class called Graph.

#### Listing 1 A large part of the Graph class

```  private int VertexCount, EdgeCount;
private boolean digraph;
public GraphDetails graphDetails;

Graph(int numVertices, boolean flag)
{
VertexCount = numVertices;
EdgeCount = 0;
digraph = flag;

graphDetails = new GraphDetails();
}

int numVertices() { return VertexCount; }
int numEdges() { return EdgeCount; }
boolean directed() { return digraph; }```

Don’t worry too much about the details of Listing 1; just try to get a feel for the overall picture and don’t be afraid to compare this with Figures 1 and 2:

• VertexCount represents the number of vertices in the graph
• EdgeCount represents the number of edges in the graph
• digraph indicates whether the vertices are directional in nature
• GraphDetails just loops through the graph and prints out the vertex and edge details

It’s probably no surprise to learn that Listing 1 is the constructor for a Java class called Graph.

To create the graph shown in Figures 1 and 2, you instantiate an object of the Graph class with a line something like this:

`Graph myGraph = new Graph(7, false);`

In keeping with the approach of helping programmers move up the value chain (see references [3 and ), the preceding code should help in getting in on the ground floor of graph programming!

Rather than having to study a lot of theory, the example code and the following explanations should provide an onramp to this overtly complex area of programming. The object construction just creates the graph and tells the object that it will have seven vertices. The edges must be added after this by using calls such as the following:

```myGraph.insertEdge(new Edge(0, 1));
myGraph.insertEdge(new Edge(0, 2));```

The above two lines of code create the edges from vertex 0 to 1 and vertex 0 to 2, respectively.

It’s not hard to see that the other edges in Figures 1 and 2 are created simply by additional calls to the method:

`myGraph.insertEdge().`

Let’s now take a look at how the graph looks once it’s been built.