Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<Windows.h>
void main()
{
int rati=7,ratj=1;
char maze [9][16] = {
{'S','S','S','S','S','S','S','S','S','S','S','S','S','S','S','S'},
{'S',' ',' ',' ','X',' ',' ',' ','X',' ','X',' ',' ',' ',' ','S'},
{'S','X','X',' ','X','X','X',' ','X',' ','X',' ','X','X','X','S'},
{'S',' ',' ',' ',' ',' ','X',' ',' ',' ','X',' ',' ',' ',' ','S'},
{'S',' ','X','X','X',' ','X',' ','X',' ','X',' ','X','X',' ','S'},
{'S',' ','X','X','X',' ','X',' ','X',' ','X',' ','X','X',' ','S'},
{'S',' ','X',' ',' ',' ',' ',' ','X',' ',' ',' ','X','X',' ','S'},
{'S',' ','X',' ',' ',' ',' ',' ','X',' ',' ',' ','X','X',' ','S'},
{'S','S','S','S','S','S','S','S','S','S','S','S','S','S','S','S'}};
char rat = 1;
char cheese = 3;
maze[7][14] = cheese;
maze[rati][ratj] = rat;
while (rati!=7 || ratj!=14)
{
for (int i=0;i<=8;i++)
{
for(int j=0;j<=15;j++)
{
printf("%c",maze[i][j]);
}
printf("\n");
}
char dirhold;
maze[rati][ratj] = ' ';
if (maze[rati-1][ratj] == ' ' && dirhold != 'd')
{
rati--;//Towards Up
dirhold = 'u';
}
else if (maze[rati][ratj+1]==' ' && dirhold != 'l')
{
ratj++;//Right
dirhold='r';
}
else if (maze[rati+1][ratj] == ' ' && dirhold !='u')
{
rati++;//Down
dirhold = 'd';
}
else if (maze[rati][ratj-1]==' ' && dirhold != 'r')
{
ratj--;//Left
dirhold = 'l';
}
/*else if (maze[rati-1][ratj] != 'X')
rati--;
else if (maze[rati+1][ratj] != 'X')
rati++;
else if (maze[rati][ratj-1]!='X')
ratj--;
else if (maze[rati][ratj+1]!='X')
ratj++;*/
maze[rati][ratj] = rat;
system ("cls");
Sleep(50);
}
getch();
}
The problem is that it is getting stuck at some point in the maze. The food is located at bottom right so obviously the preferred direction of the rat should be towards right and bottom. Please help me to implement this logic so the rat doesn't get stuck.