c++ to solve the maze...Please help

I am asked to complete a recursive function given only its function name[find_path_basic (int row, int col, char maze[ROW][COL]] to solve the maze. I tried to write the following code but then it keeps returning false so that I cant print the solved maze. The variables are defined in another .h file.

bool find_path_basic(int row, int col, char maze[ROW][COL])
{

bool success=true;



if (row==DESTINATION_ROW&&col==DESTINATION_COL){
maze[row][col]=VISITED;
success =true;
return success;
}
else if(row>ROW-1||row<1||col>COL-1||col<1){
success = false;
return success;
}
else if (maze[row][col]==WALL){
success= false;
return success;
}

else if(maze[row][col]==PATH||maze[row][col]==START){

maze[row][col]=VISITED;
if(!success && (maze[row+1][col]==PATH)){
find_path_basic(row+1,col,maze);
return success;}
if(!success && (maze[row][col+1]==PATH)){
find_path_basic(row,col+1,maze);
return success;}
if(!success && (maze[row-1][col]==PATH)){
find_path_basic(row-1,col,maze);
return success;}
if(!success && (maze[row][col-1]==PATH)){
find_path_basic(row,col-1,maze);
return success;}
if(!success){
maze[row][col]=PATH;
}
}
}

int main()
{
// You are not required and not allowed to touch this function.
char my_maze[ROW][COL];
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COL; j++)
my_maze[i][j] = MAZE[i][j];

print_maze(my_maze);
cout << endl;

bool result = false;
result = find_path_basic(START_ROW, START_COL, my_maze);
break;

if (!result)
cout << "No path found";
else
print_maze(my_maze);

// to hold the program in windows mode
char held;
cout << endl << "Enter a character to quit" << endl;
cin >> held;

return 0;
}
Last edited on
why dont you print the position (x,y) at the end of the function? and verify with the goal position? also take a piece of paper and draw the path to see if it makes sense. maybe it is just a bool issue after all.
You never test your recursive calls to see if they succeeded. The whole point of a recursive solution is to see if the nested call succeeded in finding a path.

1
2
3
4
5
6
7
8
9
10
11
12
13
maze[row][col]=VISITED;
if(!success && (maze[row+1][col]==PATH)){
find_path_basic(row+1,col,maze);  // Result of call is ignored
return success;}
if(!success && (maze[row][col+1]==PATH)){
find_path_basic(row,col+1,maze);  // Result of call is ignored
return success;}
if(!success && (maze[row-1][col]==PATH)){
find_path_basic(row-1,col,maze);  // Result of call is ignored
return success;}
if(!success && (maze[row][col-1]==PATH)){
find_path_basic(row,col-1,maze);  // Result of call is ignored
return success;}


PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.

Last edited on
Topic archived. No new replies allowed.