Using recursion to solve mazes in C++?

Prism picture Prism · Apr 19, 2013 · Viewed 7.4k times · Source

I'm trying to create a program that can solve mazes through recursion. I'm basing my code on a few steps that can be found online, specifically:

  1. if (x,y outside maze) return false
  2. if (x,y is goal) return true
  3. if (x,y not open) return false
  4. mark x,y as part of solution path
  5. if (FIND-PATH(North of x,y) == true) return true
  6. if (FIND-PATH(East of x,y) == true) return true
  7. if (FIND-PATH(South of x,y) == true) return true
  8. if (FIND-PATH(West of x,y) == true) return true
  9. unmark x,y as part of solution path
  10. return false

I have seen at least two other questions with this algorithm, but I'm pretty sure the problems weren't exactly the same.

bool path (string maze[], int x, int y){
    values val;
    bool check;
    //for (int k=0; k<val.xDim; k++) cout<<maze[k]<<endl;
    cout<<x<<":"<<y<<endl;
    if (x>val.xDim || y>val.yDim || x<0 || y<0) {cout<<"end\n"; return false;  }
    if (maze[x][y]=='x') return true;                           //If exit is reached
    if (maze[x][y]=='%' || maze[x][y]=='+') return false;       //If space is filled
    maze[x][y]='+';
    if (path(maze, x-1, y)==true) return true;
    cout<<"endtwo\n";
    if (check=path(maze, x, y+1)==true) return true;
    if (path(maze, x+1, y)==true) return true;
    if (path(maze, x, y-1)==true) return true;
    maze[x][y]='.';
    return false;
}

int main(){
    if (path(maze, val.startX-1, val.startY)==true) {
        for (int k=0; k<val.xDim; k++) cout<<maze[k]<<endl;
    } else cout<<"No solution found.\n";
}

The sample maze is (where e is the entrace and x is the exit):

%e%%%%%%%%%
%...%.%...%
%.%.%.%.%%%
%.%.......%
%.%%%%.%%.%
%.%.....%.%
%%%%%%%%%x%

Output:

-1:1
end
No solution found.

From what I can tell, the path method should begin by checking the space directly above the entrance, which is out of the maze (returning false). Following this, it should check east (and so on). However, when I run it, the function returns false and fails to continue onto the following if statements. This is shown by the fact that "end" is printed, while "endtwo" (found after the north check) is not. I'm not sure if there's some form of problem with my recursion logic or my implementation of recursion, so I'm hoping on some clarification on this.

Thanks in advance!

Answer

blue picture blue · Apr 19, 2013

Your first check in bool path(...) finds x<0 since x==-1, so the function returns false and exits, and the main program gets a false result from the call to path, prints what he has to and exits.

You should start your checks with a valid position.