We will now implement a graph in Java using adjacency matrices. Look back to the previous lesson to see our abstract base class `Graph`. Example of a digraph. We'll use this instance to explain graphs.

One way to represent graphs is through adjacency matrices. Given a graph with |V| vertices, we create an |V| x |V| 2d matrix.

If there exists an edge from one vertex (column) to another (row), we place a 1 there. If not, then we place a 0. If we had a weighted graph, we can place any non-zero element in lieu of 1.

``````    0 1 2 3 4 5 6
---------------
0 | 0 1 1 0 0 0 0
1 | 0 1 0 1 1 1 0
2 | 0 0 0 0 0 0 0
3 | 0 0 0 0 0 0 0
4 | 0 0 0 0 0 0 0
5 | 0 1 0 0 0 0 1
6 | 0 0 0 0 0 0 0``````

Let's consider some basic efficiencies. Storing this graph would take |V|2 space. Finding whether or not an edge exists, or adding an edge between two vertices would take O(1) time since all we have to do is a quick lookup.

## Checking if an edge exists

Below are two functions that check whether two vertices are connected. The `inEdgeExists(int v, int w)` method checks if there exists an edge that goes from w to v. The `outEdgeExists(int v, int w)` function checks if an edge goes from w to v.

``````| public boolean inEdgeExists(int v, int w) throws VertexOutOfBoundsException {
|     return outEdgeExists(w,v);
| }
|
| public boolean outEdgeExists(int v, int w)  throws VertexOutOfBoundsException {
|   int numV = getNumVertices();
|   if (v >= numV || w >= numV) {
|     throw new VertexOutOfBoundsException();
|   }
| }
``````

The runtime efficiency is just O(1) since we just need to access a single cell in the array.

Adding a vertex is more tedious. A naive approach to this problem would be creating a new 2d array of |V|+1 size each time a new vertex is added. We can then copy all the old elements to this new array.

A better way of doing this would be to anticipate the addition of more vertices and create a new array of 2*|V| size everytime we fill up more than 1/2 the current array. This will limit the number of instances where we have to resize our matrix.

``````public void addVertex() {
// If the number of vertices is more than half the size of our matrix,
// double the size of our matrix
int numV = getNumVertices();
if (numV > 0.5 * size) {
size = 2*size;
for (int i = 0; i < adjMatrix.length; i++) {
for (int j = 0; j < adjMatrix.length; j++) {
}
}
}
setNumVertices(numV+1);
}``````

## Deleting a Vertex

Conversely, when deleting a vertex, we can shrink our matrix's dimensions to half its original size to save space.

``````public void removeVertex() throws VertexOutOfBoundsException {
int numV = getNumVertices();
if (numV == 0) {
throw new VertexOutOfBoundsException();
}
if (size < 0.5 * numV) {
size = (int) 0.5*size;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
}
}
}
setNumVertices(numV-1);
}``````

Both adding and removing a vertex can take up to |V|2 time.

Adding an edge is as simple as inserting a value into our array matrix.

``````public void addEdge(int v, int w) throws VertexOutOfBoundsException {
int numV = getNumVertices();
if (v >= numV || w >= numV) {
throw new VertexOutOfBoundsException();
}
setNumEdges(getNumEdges()+1);
}``````

## Removing an Edge

To remove an edge, simply set that edge's cell to zero.

``````public void removeEdge(int v, int w) throws VertexOutOfBoundsException {
int numV = getNumVertices();
if (v >= numV || w >= numV) {
throw new VertexOutOfBoundsException();
}
setNumEdges(getNumEdges()-1);
}``````

## Finding in/out-degree

Finding the in or out-degree of a node takes just |V| time. Simply add 1 for every non-zero element in the corresponding column or row.

``````public int getInDegree(int v) throws VertexOutOfBoundsException {
int numV = getNumVertices();
if (v >= numV) {
throw new VertexOutOfBoundsException();
}
// Count the number of in-degrees
int count = 0;
for (int i = 0; i < getNumVertices(); i++) {
count++;
}
}
return count;
}

public int getOutDegree(int v) throws VertexOutOfBoundsException {
int numV = getNumVertices();
if (v >= numV) {
throw new VertexOutOfBoundsException();
}
// Count the number of in-degrees
int count = 0;
for (int i = 0; i < getNumVertices(); i++) {
count++;
}
}
return count;
}``````

## Finding degree sequence

The degree sequence of a graph is an ordered descending list containing the degrees of each vertex in the graph. The degree sequence is an invariant of the graph can may be used to analyze graph properties.

To find the degree sequence, we have to sum up the in and out-degrees, add them to a list, then sort them in descending order. We can place this in our abstract `Graph` class.

``````public List<Integer> getDegreeSeq() throws VertexOutOfBoundsException {
List<Integer> degreeSeq = new ArrayList<Integer>();
int degrees = 0;
for (int i = 0; i < getNumVertices(); i++) {
degrees = getInDegree(i) + getOutDegree(i);
}
Collections.sort(degreeSeq);
Collections.reverse(degreeSeq);
return degreeSeq;
} ``````

To find all neighbors of a vertex, find all non-zero elements in that vertex's row and column.

``````public List<Integer> getNeighbors(int v) throws VertexOutOfBoundsException {
int numV = getNumVertices();
if (v >= numV) {
throw new VertexOutOfBoundsException();
}
List<Integer> neighbors = new ArrayList<Integer>();
for (int i = 0; i < getNumVertices(); i++) {
}
}
return neighbors;
}``````

## Getting all two-distanced neighbors

To find all neighbors two nodes apart, we could use the `neighbors()` method twice...or...we can use a special property of matrices and square the adjacent matrix. All non-zero elements in this squared matrix contains the two-distanced neighbors! Neat! We can even cube our matrix to find all three-distanced neighbors and so on.

``````public List<Integer> getNeighborsTwoApart(int v) throws VertexOutOfBoundsException {
int numV = getNumVertices();
if (v >= numV) {
throw new VertexOutOfBoundsException();
}
List<Integer> neighbors = new ArrayList<Integer>();
int[][] sqMatrix = new int[size][size];
for (int i = 0; i < numV; i++)
for (int j = 0; j < numV; j++)
for (int k = 0; k < numV; k++)
for (int i = 0; i < numV; i++) {
if (sqMatrix[i][v] != 0 || sqMatrix[v][i] != 0) {
}
}
return neighbors;
}``````

Notice any ways you can improve this implementation? Comment below!

### Learn how data is stored

#### Data Structures and Algorithms in Java Algorithms are the procedures that software programs use to manipulate data structures. Besides clear and simple example programs, the author includes a workshop as a small demonstration program executable on a Web browser. The programs demonstrate in graphical form what data structures look like and how they operate.

\$ Check price (97+ reviews)

### Aching back from coding all day?

#### Prism Glasses Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

\$ Check price (128+ reviews)