Computer representation of graphs

Chapter: Computer representation of graphs

Perhaps the simplest way to represent a graph in a computer is by means of an adjacency matrix. For this, we think of the n nodes of a graph as being represented by the numbers 0, 1, .. n-1. The adjacency matrix is an nXn two-dimensional array adjMx of 0 and 1 such that:

For this graph:

the adjacency matrix is

01000
10110
01011
01101
00110


Exercise 3

Prove the following

Theorem: For any graph, the adjacency matrix adjMx is symmetric. In other words adjMx[i][j] = adjMx[j][i] for all possible values of i and j.


This applet generates adjacency matrices for random graphs. You enter the number of nodes that you want (29 is the maximum my display allows) and the density of edges that you'd like. The applet then makes an adjacency matrix with that many rows and columns. The density should be a number between 0 (no edges at all) and 1 (all possible edges included).

        
             
            Your browser is ignoring the <APPLET> tag!      
        


Exercise 4

Write a program to behave similarly to my applet above. Inputs should be an integer and a double. The integer should not be negative and the double should be between 0 and 1. If these conditions are not met, you should provide default values instead (see the second of my hints below). The adjacency matrix needs:

Hint: In my program I use the condition (Math.random() < density) to decide whether to include an edge or not.

Hint: Here is code I wrote to provide default values in the case of bad user input:


   JTextField howManyNodes, whatDensity;
   int numNodes;
   double density;

   ...

        try {
            numNodes = new Integer(howManyNodes.getText());
            density = new Double(whatDensity.getText());
        }
        catch (NumberFormatException nfe) {
            howManyNodes.setText("Bad data -- I'll use "+numNodes);
            whatDensity.setText("Bad data -- I'll use "+density);
        }
        if ((numNodes < 1) || (density < 0) || (density > 1)) {
            numNodes = 12;     // default
            density = .3;      // default
            howManyNodes.setText("Bad data -- use "+numNodes);
            whatDensity.setText("Bad data -- use "+density);
        }
   ...



rhyspj@gwu.edu