public void depthFirstTraversal(String source) { // Getting the index of the source vertex and // checking if the vertex really exists int sourceIndex = getIndex(source); if(sourceIndex == -1) { System.out.print("In depthFirstTraversal: vertex "); System.out.print(source); System.out.println(" is missing."); return; } // Defining and initializing the visited array boolean[] visited = new boolean[numVertices]; for(int j = 0; j < numVertices; j++) visited[j] = false; visited[sourceIndex] = true; // Defining and initializing the stack Stack s = new Stack(); s.push(new Integer(sourceIndex)); // The traversal can go on while the stack // contains a vertex to process while(!s.empty()) { // Peek at the current vertex int currentVertex = (s.peek()).intValue(); System.out.println(Vertices[currentVertex]); // Get the indices of the neighbors of the current vertex int[] neighbors = getNeighbors(currentVertex); // Scan the neighbors of the current vertex, looking // for an unvisited neighbor int j = 0; boolean found = false; while (j < neighbors.length && !found) { // If an unvisited neighbor has been found, // then push it into the stack, mark it visited // and get out of the while-loop by setting found // to true if(!visited[neighbors[j]]) { s.push(new Integer(neighbors[j])); visited[neighbors[j]] = true; found = true; } j++; } if (!found) s.pop(); } // end of while-stack-not-empty loop } // end of function