I am working on a piece of code where a robot recursively searches through a maze to find the correct path to the end. I believe I have properly implemented the recursive function, however when I try to fill the 2D array in my main function I run into the following error: Segmentation Fault (core dumped). I have shown my code below. Any help I could get would be helpful. Thank you!
#include <stdio.h>
#include <string.h>
int isValid(int x, int y)
{
if(x >= 0 && x <= 6 && y >=0 && y <= 6)
{
return 1;
}
return 0;
}
int mazeGo(char maze[6][6], char solution[6][6], int x, int y)
{
char mazeFull [6][6] =
{
{'.','#','#','#','#','#'},
{'.','.','.','.','.','#'},
{'#','.','#','#','#','#'},
{'#','.','#','#','#','#'},
{'.','.','.','#','.','.'},
{'#','#','.','.','.','#'}
};
//checks to sse if the robot is at the goal
if(x == 5 && y == 4 && isValid(x,y) == 1)
{
printf("Maze had been Solved");
solution[x][y] = '.';
return 1;
}
else if(x != 5 && y != 4 && isValid(x,y) == 1)
{
//Robot travels north
if(mazeGo(mazeFull,solution,x,y-1) == 1)
{
solution[x][y] = '.';
return 1;
}
//Robot travels East
else if(mazeGo(mazeFull,solution,x+1,y) == 1)
{
solution[x][y] = '.';
return 1;
}
//Robot travels south
else if(mazeGo(mazeFull,solution,x,y+1) == 1)
{
solution[x][y] = '.';
return 1;
}
//Robot travels west
else if(mazeGo(mazeFull,solution,x-1,y) == 1)
{
solution[x][y] = '.';
return 1;
}
else
{
solution[x][y] = '#';
return 0;
}
}
return 0;
}
int main()
{
int x = 0;
int y = 0;
char solution[6][6];
char maze [6][6] =
{
{'.','#','#','#','#','#'},
{'.','.','.','.','.','#'},
{'#','.','#','#','#','#'},
{'#','.','#','#','#','#'},
{'.','.','.','#','.','.'},
{'#','#','.','.','.','#'}
};
if(mazeGo(maze,solution,x,y) == 1)
{
for(int r = 0; r < 6; r++)
{
for(int c = 0; c < 6; c++)
{
printf("%c \n", solution[r][c]);
}
}
}
/*else
{
printf("There is no solution");
}*/
return 0;
}
Your maze is an array of 6x6 that means the positions to elements are located in [0][0] to [5][5].
Your isValid function have a bug when it let x and y be equal to 6. Try the change bellow:
int isValid(int x, int y) {
return (x >= 0 && x < 6 && y >= 0 && y < 6);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.