I am implementing depth first traversal of a graph drawn by the user using jung.
I have following code at this moment:
public <V,E> void dftdraw(Graph<V,E> g) {
V start = null;
for (V v:g.getVertices()){
if(v.toString().equals("0"))
start = v;
}
Set visited = new HashSet();
LinkedList stack = new LinkedList();
stack.add(start);
System.out.println(start.toString());
// traverse through graph in depth-first order
while (!stack.isEmpty())
{
V v = (V)stack.removeFirst();
visited.add(v);
Set neighbors = (Set) g.getNeighbors(v);
for (Iterator n_it = neighbors.iterator(); n_it.hasNext(); )
{
V w = (V)n_it.next();
if (!visited.contains(w)){
System.out.println(w.toString());
stack.addFirst(w);
}
}
}
}
But this is not doing depth first, it's first printing out the vertices connected to the starting vertex, and not like, traversing first connected vertex, then traversing through it's connected vertices.