Reputation: 85
I'm having trouble returning a desired value in a recursive call. I want it to always return 0 unless a certain condition is met, in that case it should return 1 and exit.
int check = recursion(a, b, c, d, e, f);
int recursion(int *a, int *b, int c, int d, int e, int f){
int k, dX, dY;
for(k=0;k<=b[1]-1;k++){
dX = b[k*4+3] - e;
dY = b[k*4+2] - f;
if(((dX == 1 || dX == -1) && (dY == 0))){
if(b[k*4+4] == 1) return 1;
e = b[k*4+3];
f = b[k*4+2];
b[k*4+2] = b[k*4+3] = 0;
recursion(a, b, c, d, e, f);
}
if(((dY == 1 || dY == -1) && (dX == 0))){
if(b[k*4+4] == 1) return 1;
e = b[k*4+3];
f = b[k*4+2];
b[k*4+2] = b[k*4+3] = 0;
recursion(a, b, c, d, e, f);
}
}
return 0;
}
A lot of irrelevant information has been removed, but as you can see if b[k*4+4] == 1 at anypoint, check should then equal 1. Otherwise, return 0 and check will = 0. It completes a basic traversal, which I know is completing correctly and is even stopping at the terminating condition (b[k*4+4] == 1) but it isn't returning the correct value.
Currently, it is ALWAYS returning 0. Check always equals 0, although it is stopping once the condition is met. I also tried removing the ending return 0; although check still equals zero...
Upvotes: 0
Views: 236
Reputation: 3816
You need to do return recursion(a, b, c, d, e, f);
instead of just recursion(a, b, c, d, e, f);
. Otherwise, the result of those recursive calls will be lost.
edit: to not prematurely exit your loop, you can do this:
int check = recursion(a, b, c, d, e, f);
int recursion(int *a, int *b, int c, int d, int e, int f){
int k, dX, dY;
for(k=0;k<=b[1]-1;k++){
dX = b[k*4+3] - e;
dY = b[k*4+2] - f;
if(((dX == 1 || dX == -1) && (dY == 0))){
if(b[k*4+4] == 1) return 1;
e = b[k*4+3];
f = b[k*4+2];
b[k*4+2] = b[k*4+3] = 0;
if(recursion(a, b, c, d, e, f) == 1)
return 1;
}
if(((dY == 1 || dY == -1) && (dX == 0))){
if(b[k*4+4] == 1) return 1;
e = b[k*4+3];
f = b[k*4+2];
b[k*4+2] = b[k*4+3] = 0;
if(recursion(a, b, c, d, e, f) == 1)
return 1;
}
}
return 0;
}
Upvotes: 0
Reputation: 1768
You just need to check the return values of your recursive calls, i.e.,
return recursion(a, b, c, d, e, f);
Upvotes: 1