0

I've been trying to implement a DFS search of a Graph as part of my project, but I've been having trouble with figuring exactly how the recursion is meant to work..., I think my code is correct, but the results show otherwise.

public void RecursionHelper(HashSet seen2, int startVertex2, LinkedStack components2, boolean[] alert2){

    seen2.add(startVertex2);
    for(int i = 0; i < matrix.get(startVertex2).size() ; i++){
        boolean b = helper(matrix.get(startVertex2), i);

        if(matrix.get(startVertex2).get(i) !=0 && !seen2.contains(i)){
            int p = i;
            RecursionHelper(seen2, i , components2, alert2);
            if(b = true && alert2[startVertex2] == false){
                components2.push(startVertex2);
                alert2[startVertex2]= true;
            }

        }
        else if(b = true && alert2[startVertex2] == false){
            components2.push(startVertex2);
            alert2[startVertex2]= true;
        }

    }
}

Here is my helper method for telling if the current index is the one with the last 1 in the ArrayList

public boolean helper(ArrayList<Integer> k, int o){
    boolean last = false;
    int capture = 0; //the index of the last connection in the arraylist
    if(k.size() == 1){
        return true;
    }

    for(int i = k.size() -1 ; i > 0; i--){
        if(k.get(i) == 1){
            capture = i;
        }
    }
    if
    ( o  == capture){
        last = true;

    }
    return last;
}

matrix is a 2D arraylist that I'm using as an adjacency matrix to display the graph.

  • `if (b = true ...)` doesn't test `b` to see if it's `true`, it **sets** `b` to `true`. This should be `if (b == true...)` but it really should just be `if (b ...`. You never need to say `x == true` or `x == false` to test a `boolean`; just use `x` and `!x`, and then you avoid problems like the one you're having. I'm sure that's not the only bug. I suspect your `helper` isn't working right, but I'm not really sure what you're trying to do. Try writing some unit tests for `helper`, i.e. give it some different parameters and make sure it's returning what you think it should. – ajb Jun 03 '17 at 04:55
  • wow, thanks a lot, you were right about setting b to true. I changed it and at the very least my stack is almost in the right order now..., yeah, I'll do some more testing on helper. – Nicholas Yong Jun 03 '17 at 05:03
  • the whole thing is working now, I was missing a break in the helper method to stop the loop once it found the first 1 – Nicholas Yong Jun 03 '17 at 05:18

0 Answers0