Data Structures, Algorithms, & Applications in Java
Chapter 17, Exercise 21
Let
a[n][n + 1] be the two-dimensional array used
to store the adjacency matrix
A of an n vertex graph.
The diagonal entries of
A are not stored in
a. However, all diagonal elements
of A are required to be zero.
Elements A(i,j) with i < j
are in the upper triangle of A and are stored
in a[i-1][j-1].
Elements A(i,j) with i > j
are in the lower triangle of A and are stored
in a[i-2][j-1].
With these observations, the code for set
and get takes the form given below.
A test program and output
appear
in the files GraphAdjacencyMatrix.*.
public class GraphAdjacencyMatrix
{
// data members
boolean [][] a; // adjacency array
// constructor
public GraphAdjacencyMatrix(int theVertices)
{
// validate theVertices
if (theVertices < 0)
throw new IllegalArgumentException
("number of vertices must be >= 0");
a = new boolean [theVertices][theVertices + 1];
}
// methods
/** throws IndexOutOfBoundsException when
* either i or j is not between 1 and a.length */
void checkIndex(int i, int j)
{
if (i < 1 || j < 1 || i > a.length || j > a.length)
throw new IndexOutOfBoundsException
("i = " + i + " j = " + j + " vertices = "
+ a.length);
}
/** return A(i,j) */
public int get(int i, int j)
{
checkIndex(i, j);
// diagonal entry is always zero
if (i == j)
return 0;
// not a diagonal entry
if (i < j)
// upper triangle
return (a[i-1][j-1]) ? 1 : 0;
else
// lower triangle
return (a[i-2][j-1]) ? 1 : 0;
}
/** set A(i,j) = newValue */
public void set(int i, int j, int newValue)
{
checkIndex(i, j);
// validate newValue
if (newValue < 0 || newValue > 1)
throw new IllegalArgumentException
("new value must be 0 or 1");
// store newValue
if (i < j)
// upper triangle
a[i-1][j-1] = (newValue == 1) ? true : false;
else
if (i > j)
// lower triangle
a[i-2][j-1] = (newValue == 1) ? true : false;
else
// diagonal entry
if (newValue == 1)
throw new IllegalArgumentException
("diagonal value must be 0");
}
}