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.
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)
这是一道模拟题,只要按照题目的意思一步一步的实现,就能成功。
exit的条件是大于行、列,或者小于0,loop的条件是第一次出现走过的位置。
#include<stdio.h>
#include<string.h>
int main()
{
char map[11][11],m[11][11];//map代表grid,m记录走过的地方(m可以不要,直接对map进行操作,但要记录位置比较麻烦)
int row,col,f,i,flag,rr,cc;
while(1)
{
flag = 0;
scanf("%d%d%d",&row, &col, &f);
int r = 0,c = f - 1;
if(0 == row && 0 == col)
break;
for(i = 0; i < row; i++)
scanf("%s",map[i]);
memset(m,0,sizeof(m));
i = 1;
while(flag == 0)
{
//rr、cc来记录对一个指令的行和列,flag标记是exit了还是循环了
rr = r;
cc = c;
switch(map[r][c])
{
case 'E':
if( c + 1 >= col)
flag = 1;
else
{
m[r][c] = i++;
if(m[r][++c] > 0)
flag = 2;
}
break;
case 'N':
if( r - 1 < 0 )
flag = 1;
else
{
m[r][c] = i++;
if(m[--r][c] > 0)
flag = 2;
}
break;
case 'W':
if( c - 1 < 0)
flag = 1;
else
{
m[r][c] = i++;
if(m[r][--c] > 0)
flag = 2;
}break;
case 'S':
if( r + 1 >= row)
flag = 1;
else
{
m[r][c] = i++;
if(m[++r][c] > 0)
flag = 2;
}break;
}
}
if(1 == flag)
printf("%d step(s) to exit\n",i);
else
printf("%d step(s) before a loop of %d step(s)\n",m[r][c] - 1,m[rr][cc] - m[r][c] + 1 );
}
return 0;
}