Stack Report
Stack Report
A Maze is given as N*M binary matrix of blocks and there is a rat initially at (0, 0) .
maze[0][0] and the rat wants to eat food which is present at some given block in the
maze (fx, fy). In a maze matrix, 0 means that the block is a dead end and 1 means that
the block can be used in the path from source to destination. The rat can move in any
direction (not diagonally) to any block provided the block is not a dead end.
#include <stdio.h>
Code
#include <stdlib.h>
#define MAX 20
#define n 4
#define m 5
int stack[MAX];
int top = -1;
int main()
{
//input Maze matrix
int maze[n][m],fx,fy;
printf("enter maze %dx%d:\n",n,m);
for (int i=0; i<n; i++)
for (int j=0; j<m; j++)
scanf("%d",&maze[i][j]);
printf("enter fx & fy:");
scanf ("%d%d",&fx,&fy);
int dir =0,i=0,j=0;
/*dir=0 try right direction.
dir=1 try down direction.
dir=2 try left direction.
dir=3 try Up direction.
*/
while (i!=fx||j!=fy)
{
switch(dir)
{
case 0://right direction.
if(j+1<m)
{
if(maze[i][j+1]==1)
{
push(0);
j++;
dir =0;
maze[i][j]=0;
else dir++;
break;
}
case 1://down direction.
if(i+1<n)
{
if(maze[i+1][j]==1)
{
push(1);
i++;
dir =0;
maze[i][j]=0;
}
else dir++;
break;
}
case 2://left direction.
if(j-1>=0)
{
if(maze[i][j-1]==1)
{
push(2);
j--;
dir =0;
maze[i][j]=0;
}
else dir++;
break;
}
case 3://up direction.
if(i-1>=0)
{
if(maze[i-1][j]==1)
{
push(3);
i--;
dir =0;
maze[i][j]=0;
}
else dir++;
break;
}
default :
dir=pop();
switch(dir)
{
case 0://retract right direction.
j--;
break;
case 1://retract down direction.
i--;
break;
case 2://retract left direction.
j++;
break;
case 3://retract up direction.
i++;
break;
}
dir++;
}
}
printf("solution for maze is :\n");
display();
return 0;
}
Test cases
Case 1:
enter maze 4x5:
10110
11101
01011
11111
enter fx & fy:2 3
solution for maze is :
down
right
down
down
right
right
right
up
left
Case 2:
enter maze 4x5:
10000
11010
11001
01111
enter fx & fy:3 3
solution for maze is :
down
right
down
Down
right
right
Case 3:
enter maze 4x5:
10111
11101
00011
11111
enter fx & fy:3 1
solution for maze is :
down
right
right
up
right
right
down
down
down
left
left
left
Case 4:
enter maze 4x5:
10110
11101
01011
11111
enter fx & fy:0 3
solution for maze is :
down
right
right
up
right