recursion – Java return problem – Education Career Blog

  public void question(int col, int n, Node<Integer> part_soln) {
        if (col==0) stack.push(part_soln);
        else for (int row=1; row<=n; row++)
              { if (!exists(row,part_soln) && !unsafe(col,row,col+1,part_soln)) 
                  { Node<Integer> new_soln = new Node<Integer>(row,part_soln);
                    question(col-1,n,new_soln);
                  }
              }
    }  

i was inserting part_soln into the stack, but now i want to get the first part_soln instead of the stack, i will break the loop once i get the part_soln, i modify the question become

  public void question(int col, int n, Node<Integer> part_soln) {
        if (col==0) return part_soln;
        else for (int row=1; row<=n; row++)
              { if (!exists(row,part_soln) && !unsafe(col,row,col+1,part_soln)) 
                  { Node<Integer> new_soln = new Node<Integer>(row,part_soln);
                    question(col-1,n,new_soln);
                  }
              }
return null;
}

the problem occurs, i cant get the first element in the stack but keep getting “null” as an answer, any suggestion?

,

In the second version of question(), you have only two return statements, and the second returns null whenever col != 0.

So you seem to have messed up your recursion scheme, because even though question() calls itself recursively within the loop, the return value is not used.

It would help to know what the method is supposed to do. But anyway, my attempt to fix it based on the information you provided (you want to find and return the first suitable solution) is

public Node<Integer> question(int col, int n, Node<Integer> part_soln) {
    if (col==0) 
        return part_soln;
    else for (int row=1; row<=n; row++) {
        if (!exists(row,part_soln) && !unsafe(col,row,col+1,part_soln)) {
            Node<Integer> new_soln = new Node<Integer>(row,part_soln);
            Node<Integer> ret = question(col-1,n,new_soln);
            if (ret != null)
                return ret;
        }
    }
    return null;
}

The difference is that I store the return value from the recursive call and if it is not null, return it immediately.

Leave a Comment