Robot Motion | ||||||
| ||||||
Description | ||||||
| ||||||
Input | ||||||
There will be one or more grids for robots to navigate. The data for each is in the following form. On the first line are three integers separated by blanks: the number of rows in the grid, the number of columns in the grid, and the number of the column in which the robot enters from the north. The possible entry columns are numbered starting with one at the left. Then come the rows of the direction instructions. Each grid will have at least one and at most 10 rows and columns of instructions. The lines of instructions contain only the characters N, S, E, or W with no blanks. The end of input is indicated by a row containing 0 0 0.
| ||||||
Output | ||||||
For each grid in the input there is one line of output. Either the robot follows a certain number of instructions and exits the grid on any one the four sides or else the robot follows the instructions on a certain number of locations once, and then the instructions on some number of locations repeatedly. The sample input below corresponds to the two grids above and illustrates the two forms of output. The word "step" is always immediately followed by "(s)" whether or not the number before it is 1.
| ||||||
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) |
题目大意:每一个gird(格子)上都标记有下一步要走到哪里,问如果能够走出n*m大的地图,就按照样例1输出,否则如果走出了环,先输出在走到环起点之前走了多少步,然后输出在环里能重复走的步数,多组输入,0 0 0break;
思路:简单模拟,牢记初始化,注意起点的标记。
AC代码:
#include<stdio.h>
#include<string.h>
using namespace std;
int output[1050][1050];
char a[1050][1050];
//n-up 1 13
//s-down 2 18
//e-right 3 4
//w-left 4 22
int n,m,t;
void solve()
{
memset(output,0,sizeof(output));
output[0][t]=1;
int flag=0;
int ans=0;
int step=1;
int x=0;
int y=t;
while(1)
{
//printf("%d %d %d\n",x,y,output[x][y]);
int cur=a[x][y]-'A';
if(cur==13)
{
x-=1;
}
if(cur==18)
{
x+=1;
}
if(cur==4)
{
y+=1;
}
if(cur==22)
{
y-=1;
}
if(x<0||y<0||x>=n||y>=m)
break;
step++;
if(output[x][y]==0)
output[x][y]=step;
else
{
//printf("%d %d\n",x,y);
ans=output[x][y];
flag=step-output[x][y];
break;
}
}
if(flag==0)
printf("%d step(s) to exit\n",step);
else
printf("%d step(s) before a loop of %d step(s)\n",ans-1,flag);
}
int main()
{
while(~scanf("%d%d%d",&n,&m,&t))
{
if(n==0&&m==0&&t==0)break;
for(int i=0;i<n;i++)
{
scanf("%s",a[i]);
}
t--;
solve();
}
}