import java.util.*; public class UndirectedBreadthFirstMatrix { int numVertices; // Number of vertices, given as input. int numEdges; // We keep track of the number of edges. boolean isWeighted; // Is this a weighted graph? boolean useMatrix = true; // Adjacency-matrix or list? double [][] adjMatrix; // The matrix. Note: we use "double" to store // "double" weights, if the graph is weighted. int[] visitOrder; // visitOrder[i] = the i-th vertex to be visited in order. int visitCount; // We will track visits with this counter. LinkedList queue; // The queue for breadth-first, a java.util.LinkedList. public void initialize (int numVertices, boolean isWeighted) { // Store: this.numVertices = numVertices; this.isWeighted = isWeighted; if (useMatrix) { // Create the adjacency matrix. adjMatrix = new double [numVertices][]; for (int i=0; i= numVertices) ) return true; return false; } // Insert a given input edge. public void insertUndirectedEdge (int startVertex, int endVertex, double weight) { // Check whether vertex is valid. if ( outOfBounds (startVertex) || outOfBounds (endVertex) ) { System.out.println ("ERROR: out of bounds: start=" + startVertex + " end=" + endVertex); return; } // Matrix representation: if (useMatrix) { // If already inserted, flag an error. if (adjMatrix[startVertex][endVertex] != 0) { System.out.println ("ERROR: edge already inserted: (" + startVertex + "," + endVertex +")"); return; } // Unweighted graph: use weight 1.0. if (! isWeighted) { adjMatrix[startVertex][endVertex] = 1.0; adjMatrix[endVertex][startVertex] = 1.0; } else { adjMatrix[startVertex][endVertex] = weight; adjMatrix[endVertex][startVertex] = weight; } numEdges ++; return; } // end-use-Matrix. // Adj-list implementation ... (not shown) } // Initialize visit information before search. void initSearch () { // IMPORTANT: all initializations will use "-1". We will test // equality with "-1", so it's important not to change this cavalierly. visitCount = -1; for (int i=0; i 0) && (i != v) ) { // 3.4.1.1 If not visited, place in queue. if (visitOrder[i] == -1) { queue.addLast (new Integer(i)); } } // endif } // end-for } // end while } }