Description
A robot has been programmed to follow the instructions in its path. Instructions for the next direction the robot is to move are laid down in a grid. The possible instructions are
N north (up the page)
S south (down the page)
E east (to the right on the page)
W west (to the left on the page)
For example, suppose the robot starts on the north (top) side of Grid 1 and starts south (down). The path the robot follows is shown. The robot goes through 10 instructions in the grid before leaving the grid.
Compare what happens in Grid 2: the robot goes through 3 instructions only once, and then starts a loop through 8 instructions, and never exits.
You are to write a program that determines how long it takes a robot to get out of the grid or how the robot loops around.
Input
Output
Sample Input
3 6 5 NEESWE WWWESS SNWWWW 4 5 1 SESWE EESNW NWEEN EWSEN 0 0 0
Sample Output
10 step(s) to exit 3 step(s) before a loop of 8 step(s)
#include<stdio.h>
int main(){
int n,m,t;
while(scanf("%d%d%d",&n,&m,&t)!=EOF&&(n||m)){
int d[n][m];
char map[n][m];
int i,j,flag;
flag=0;
int loop=0,step=1;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
d[i][j]=0;
for(i=0;i<n;i++){
scanf("%s",&map[i]);
}
int x=0,y=t-1;
while(1){
if(map[x][y]=='N'&&!d[x][y]){
d[x][y]=step;
x--;
}
else if(map[x][y]=='S'&&!d[x][y]){
d[x][y]=step;
x++;
}
else if(map[x][y]=='E'&&!d[x][y]){
d[x][y]=step;
y++;
}
else if(map[x][y]=='W'&&!d[x][y]){
d[x][y]=step;
y--;
}
else if(d[x][y]>0){
step--;
loop=step-d[x][y]+1;
flag=1;
break;
}
else if(x<0||x>=n||y<0||y>=m){
step--;break;
}
step++;
}
if(flag) printf("%d step(s) before a loop of %d step(s)\n",step-loop,loop);
else printf("%d step(s) to exit\n",step);
}
return 0;
}