原题:
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.
题意:
模拟题,输入一张地图,四个字母分别代表上下左右(东西南北),机器人从第一行某一个位置进入,然后进入哪个格子就按照那个格子进行移动,如果能离开地图就输出要走多少步,如果不能离开地图输出要走多少步进入循环和循环多少步
题解:
就是一个比较简单的模拟题,额外加一个数组记录是否走过,然后设置一个标记来记录会不会回到曾经走到过的地方,如果回到了走过的地方,那就记录下到目前为止走了n步,然后再从头走一遍一直走到这个点,记录走了m步,那么也就是要循环n-m步,如果没有到走过地方就离开了地图,那就直接输出n
代码:(AC)
#include<iostream>
#include<cstring>
using namespace std;
char map[500][500];
int visited[500][500];
int main()
{
int line,row,first;
while(cin>>line>>row>>first)
{
if(line+row+first==0)
break;
else
{
int i,j;
for(i=0;i<line;i++)
{
for(j=0;j<row;j++)
visited[i][j]=0;
}
for(i=0;i<line;i++)
{
for(j=0;j<row;j++)
cin>>map[i][j];
}
int xposition=first-1;
int yposition=0;
int step=0;
int flag=0;
int notloop=0;
while(xposition>=0&&yposition>=0&&xposition<row&&yposition<line)
{
if(!visited[yposition][xposition])
{
visited[yposition][xposition]=1;
step++;
if(map[yposition][xposition]=='W')
xposition--;
else if(map[yposition][xposition]=='E')
xposition++;
else if(map[yposition][xposition]=='S')
yposition++;
else
yposition--;
}
else
{
visited[yposition][xposition]=0;
flag=1;
break;
}
}
if(flag)
{
xposition=first-1;
yposition=0;
while(visited[yposition][xposition])
{
notloop++;
if(map[yposition][xposition]=='W')
xposition--;
else if(map[yposition][xposition]=='E')
xposition++;
else if(map[yposition][xposition]=='S')
yposition++;
else
yposition--;
}
cout<<notloop<<" step(s) before a loop of "<<step-notloop<<" step(s)"<<endl;
}
else
cout<<step<<" step(s) to exit"<<endl;
}
}
return 0;
}