package username.graph; import java.util.Iterator; /** * An iterator for successors. * * @author Samuel A. Rebelsky * @version 1.0 of April 2006 */ public class MatrixSuccessors implements Iterator { // +------------------+-------------------------------------------------- // | Design Decisions | // +------------------+ /* (1) We keep a link to the the underlying adjacency matrix, rather than building a new array, vector, list, or whatever. (2) To iterate, we keep track of a position within that matrix. (3) We use nextSuccessor to keep track of the index of the next successor to be iterated. (4) If there are no successors, we set nextSuccessor to a value at least as large as this.size. */ // +--------+------------------------------------------------------------ // | Fields | // +--------+ /** The source. */ int source; /** The size of the underlying graph. */ int size; /** An adjaceny matrix to represent the edges. */ int[][] edges; /** The index of the next successor. */ int nextSuccessor; // +--------------+------------------------------------------------------ // | Constructors | // +--------------+ public MatrixSuccessors(int _source, int _size, int[][] _edges) { this.source = _source; this.size = _size; this.edges = _edges; this.nextSuccessor = 0; this.findSuccessor(); } // MatrixSuccessors(int, int[][]) // +------------------+-------------------------------------------------- // | Iterator Methods | // +------------------+ /** * Determine whether there are any more successors. */ public boolean hasNext() { return this.nextSuccessor >= this.size; } // hasNext() /** * Get the next successor. */ public Integer next() { // Grab the successor int succ = this.edges[this.source][this.nextSuccessor]; // Advance. ++nextSuccessor; // Find the next edge. findSuccessor(); // That's it. return succ; } // next() /** * Remove something. Not implements. */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } // remove() // +---------------+----------------------------------------------------- // | Local Helpers | // +---------------+ /** * Advance nextSuccessor to the first successor at or after its current * position. */ void findSuccessor() { while ( (this.nextSuccessor < this.size) && (this.edges[this.source][this.nextSuccessor] != MatrixWDG.NOEDGE) ) { ++this.nextSuccessor; } // while } // findSuccessor } // class MatrixSuccessors