# Thread: Problem with recursive function

1. ## Problem with recursive function

Hello,

I am writing a program that navigates a maze. I am trying to use a recursive function to do so. My problem is the function stops working partway through. This is the maze I am using:

ooooooooooo
o ```````` o
o`ooooooo `o
o+o```````o
ooo`ooooooo
o\$o``````\$o
o`o`ooooooo
o````````-o
ooooooooooo

The function gets as far as this and quits

ooooooooooo
o ########o
o #ooooooo `o
o+o```````o
ooo`ooooooo
o\$o``````\$o
o`o`ooooooo
o````````-o
ooooooooooo

Code:
```void findDollar ( maz_t  *t){ // function to find checkpoint

int i, j;

for (i=0;i<row;i++){  // loop to find a checkpoint
for(j=0;j<column;j++){
if (t->map[i][j] == '\$'){
t->dollarX = i;
t->dollarY = j;
}
}
}

if(t->map[t->startx-1][t->starty] != 'o' && t->map[t->startx-1][t->starty] != '#'){ // moves up
t->map[t->startx-1][t->starty] = '#';
t->startx = t->startx-1;

}
else if(t->map[t->startx+1][t->starty] != 'o' && t->map[t->startx+1][t->starty] != '#'){ // moves down
t->map[t->startx+1][t->starty] = '#';
t->startx = t->startx+1;
}
else if(t->map[t->startx][t->starty-1] != 'o' && t->map[t->startx][t->starty-1] != '#'){ // moves to the left
t->map[t->startx][t->starty-1] = '#';
t->starty = t->starty-1;
}

else if(t->map[t->startx][t->starty+1] != 'o' && t->map[t->startx][t->starty+1] != '#'){ // moves to the right
t->map[t->startx][t->starty+1] = '#';
t->starty = t->starty+1;
}

if (t->startx != t->dollarX && t->starty != t->dollarY){  // If the checkpoint has not been reached, call function again.
findDollar(t);
}

}// end function```
I'm assuming that it's something with the way I am directing it to move down, but I can't see the problem. Any help would be greatly appreciated.

2. I haven't totally dissected this but based on what you say don't you think the problem will be here:

Code:
```			if (t->startx != t->dollarX && t->starty != t->dollarY){  // If the checkpoint has not been reached, call function again.
findDollar(t);
}```

3. Sorry, I don't understand.

I also tried using
Code:
```	while (t->startx != t->dollarX && t->starty != t->dollarY){
findDollar(t);
}```
and

Code:
```			while (t->map[t->dollarX][t->dollarY] != '#'){
findDollar(t);
}```
Ive gotten the same results with both. Anything else I tried gives me a stack overflow.

4. You can do this much easier with a stack.

1. Pick a starting point
2. Push current location on the stack
3. Pick a random direction
4. If open, move there and goto 2
5. If not open, pop off the stack and goto 3
6. Repeat until all cells have been checked.

5. Unfortunately for me, this assignment is due in an hour and a half. I think I'm stuck with trying to figure out this method.

6. From the code it's not obvious what's going on, so post the algorithm you're using to navigate this maze.