I have this working code for finding path between source to destination non-recursively. I would like to implement recursively, but I am having difficulty in how to do it.
This is my code for non-recursive implementation
public boolean depthFirstSearch(String name1, String name2){
Vertex source = vertexMap.get(name1);
Vertex dest = vertexMap.get(name2);
clearAll();
Stack<Vertex> stack = new Stack<Vertex>();
source.setVisited(true);
stack.push(source);
while(!stack.isEmpty()){
source = stack.peek();
System.out.println(source.name);
if (dest.name.equals(source.name))
return true;
Vertex v = adjacentUnvisitedVertex(source);
if (v!=null){
v.setVisited(true);
v.prev=source;
stack.push(v);
}
else stack.pop();
}
if (!source.name.equals(dest.name)){
System.out.println("destination cannot be reached");
return true;
}
else return false;
}
private Vertex adjacentUnvisitedVertex(Vertex v){
for (Edge e : v.adj){
if (!e.target.isVisited){
return e.target;
}
}
return null;
}
while a simple DFS recursive implementation is here, that visit all nodes:
static void dfs (Graphnode n) {
n.setVisited( true );
Iterator it = n.getSuccessors().iterator();
while (it.hasNext()) {
Graphnode m = (Graphnode)it.next();
if (! m.getVisited()) dfs(m);
}
}
I would like to implement for finding path between two nodes A and B. so the dfs would take two nodes and find path between recursively.
Thanks