I am trying to implement the recursive version of DFS for depth first search between two nodes. Here is my code. The method will return true if there is a path that exists and it also updates the prev field of the node to keep track of the path. I have implemented this non-recursive way using stacks and it works fine which is here.. This one is not working. That is it is not giving me the path from Node A to Node B. It always seem to return false.
public boolean recursiveDFS(String start, String end){
clearAll();
Vertex source = vertexMap.get(start);
Vertex dest = vertexMap.get(end);
clearAll();
return recursiveDFShelper(source,dest);
}
private boolean recursiveDFShelper(Vertex sor, Vertex des){
if (!sor.name.equals(des.name)){
sor.setVisited(true);
Iterator<Edge> it = sor.adj.iterator();
while (it.hasNext()){
Vertex v = it.next().target;
if(!v.isVisited){
sor.prev=v;
recursiveDFShelper(v, des);
}
}
return false;
}
else
return true;
}
EDIT: After below suggestions, I have this code
public boolean recursiveDFS(String start, String end){
clearAll();
Vertex source = vertexMap.get(start);
Vertex dest = vertexMap.get(end);
clearAll();
return recursiveDFShelper(source,dest);
}
private boolean recursiveDFShelper(Vertex sor, Vertex des){
//System.out.println(sor.name);
if (!sor.name.equals(des.name)){
sor.setVisited(true);
System.out.println(sor.adj);
Iterator<Edge> it = sor.adj.iterator();
while (it.hasNext()){
Vertex v = it.next().target;
if(!v.isVisited){
v.prev=sor;
System.out.printf("prev of %s is %s\n",sor,sor.prev);
return recursiveDFShelper(v, des);
}
}
//System.out.println("returning false");
return false;
}
else {
System.out.println("returning true");
return true;
}
}
for a given directed graph like this,
A B
B C
C D
A E
E D
it is able to find the correct path from A to D, but fails from A to E which is just one node away.