/** Source code example for "A Practical Introduction to Data Structures and Algorithm Analysis, 3rd Edition (Java)" by Clifford A. Shaffer Copyright 2008-2011 by Clifford A. Shaffer */ // Graph operation main function. // To use: java -ea GraphTest import java.io.*; import java.util.*; public class GraphTest extends junit.framework.TestCase { static final int UNVISITED = 0; static final int VISITED = 1; // Create a graph from file static Graph createGraph(BufferedReader file, Graph G) throws IOException { String line = null; StringTokenizer token; boolean undirected = false; int i, v1, v2, weight; assert (line = file.readLine()) != null : "Unable to read number of vertices"; while(line.charAt(0) == '#') assert (line = file.readLine()) != null : "Unable to read number of vertices"; token = new StringTokenizer(line); int n = Integer.parseInt(token.nextToken()); G.Init(n); for (i=0; i Q = new AQueue(G.n()); Q.enqueue(start); G.setMark(start, VISITED); while (Q.length() > 0) { // Process each vertex on Q int v = Q.dequeue(); PreVisit(G, v); // Take appropriate action for (int w = G.first(v); w < G.n(); w = G.next(v, w)) if (G.getMark(w) == UNVISITED) { // Put neighbors on Q G.setMark(w, VISITED); Q.enqueue(w); } PostVisit(G, v); // Take appropriate action } } /** * This method is automatically called once before each test case * method, so that all the variables are cleanly initialized for * each test. */ public void setUp() { out = new StringBuffer(100); } public void testGraph() throws IOException { BufferedReader f; f = new BufferedReader(new InputStreamReader(new FileInputStream("testfile.gph"))); Graph G = new Graphl(); createGraph(f, G); BFS(G, 0); assertEquals(out.toString(), "0 0 2 2 4 4 1 1 3 3 5 5 "); } }