package username.graph; import java.util.Iterator; /** * An implementation of weighted, directed graphs using adjaceny * matrices. * * @author Samuel A. Rebelsky * @version 1.0 of April 2006 */ public class MatrixWDG implements WDG { // +------------------+-------------------------------------------------- // | Design Decisions | // +------------------+ /* (1) We represent the graph with an adjaceny matrix (a two-dimensional array). edges[s][t] is the weight of the edge from s to t. (2) We do not permit negative weights. (3) We use the constant NOEDGE to represent that there is no edge from s to t. */ // +-----------+--------------------------------------------------------- // | Constants | // +-----------+ /** Indicate that there's no edge from source to target. */ static final int NOEDGE = -1; // +--------+------------------------------------------------------------ // | Fields | // +--------+ /** The number of vertices. */ int size; /** An adjaceny matrix to represent the edges. */ int[][] edges; // +--------------+------------------------------------------------------ // | Constructors | // +--------------+ public MatrixWDG(int _size) { this.size = _size; this.edges = new int[_size][_size]; for (int s = 0; s < _size; s++) { for (int t = 0; s < _size; t++) { edges[s][t] = NOEDGE; } // for } // for } // MatrixWDG(int) // +-----------+--------------------------------------------------------- // | Observers | // +-----------+ /** * Determine the number of vertices in the graph. */ public int size() { return this.size; } // size() /** * Determine whether there is an edge from source to target * in the graph. */ public boolean edge(int source, int target) throws Exception { return (0 <= source) && (source < this.size) && (0 <= target) && (target < this.size) && (edges[source][target] != NOEDGE); } // edge(int,int) /** * Determine the weight of the edge from source to target. */ public int weight(int source, int target) throws Exception { return edges[source][target]; } // weight(int, int) /** * Get the successors of source. */ public Iterator successors(int source) { return new MatrixSuccessors(source, size, edges); } // successors(int) /** * Get the predecessors of target. */ public Iterator predecessors(int target) { return new MatrixPredecessors(target, size, edges); } // successors(int) // +----------+---------------------------------------------------------- // | Mutators | // +----------+ /** * Create an edge from s to t of weight w. If * s or t is at least as large as size, throws an exception. */ public void makeEdge(int s, int t, int w) throws Exception { if (s >= this.size) { throw new Exception("Invalid source: " + s); } if (t >= this.size) { throw new Exception("Invalid target: " + t); } edges[s][t] = w; } // makeEdge(int, int) /** * Delete the edge from s to t. */ public void deleteEdge(int s, int t) { edges[s][t] = NOEDGE; } // deleteEdge(int,int) } // class MatrixWDG