1

This is my implementation for the reachable() of a graph using depth first search. It looks for a possible path from vertex 1 (v1) to another vertex (v2) I got some results correctly and some are wrong. I have tried as many ways as I can to debug, but I couldn'd figure out where is wrong. Any help is appreciated. Thank you

public boolean isReachable(V v1, V v2) {
            Stack<V> path = new Stack<V>();
            return isReachableHelper(v1, v2, path);
        }

}

public boolean isReachableHelper(V v1, V v2, Stack<V> path){
        path.push(v1);
        v1.setVisited(true); //set the vertex as being visited

        if (v1.vertex().equals(v2.vertex())){ //check whether vertex' values are equal
            return true;
        }

            //loop through all vertex that are neighbors of v1
        for (V neighbor : super.neighbors(v1)){ 
            if (!neighbor.visited ){ //if the neighbor is not visited before
                return isReachableHelper(neighbor, v2, path); //recursive call
            }
        }

        path.pop(); //no path was found
        return false;
    }

1 Answer 1

2

The Problem: In your for loop, you only ever expand the first non-visited neighbor node and then immediately return the value of that recursive call. I.e., if no path can be found via the first neighbor of v1, you just 'give up' without looking at the other neighbors.

Instead, you have to try all neighbor nodes until you find one for which the recursive call returns true. In this case, you have found a path and you can return true; otherwise, your method correctly pops the last node from the path and returns false (backtracking).

for (V neighbor : super.neighbors(v1)){ 
    if (!neighbor.visited ){ //if the neighbor is not visited before
        if (isReachableHelper(neighbor, v2, path)) { //recursive call
            return true; // we found a path!
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

i was just writing up the same thing.
@Mikeb Sorry about that! ^^; There really should be an indicator for answers-in-progress...
nah, I like your explanation better than where I was going anyway.
perfect explanation. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.