Robot Motion
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 5352 Accepted Submission(s): 2492

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.
3 6 5 NEESWE WWWESS SNWWWW 4 5 1 SESWE EESNW NWEEN EWSEN 0 0
10 step(s) to exit 3 step(s) before a loop of 8 step(s)
==============================
简单的模拟
当一个点走过两次就说明一定会一直重复走下去
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char map[1111][1111];
int vis[1111][1111];
int n,m,s;
bool check(int x,int y)
{
if(x>=1&&x<=n&&y>=1&&y<=m) return 1;
else return 0;
}
int main()
{
while(~scanf("%d%d%d",&n,&m,&s))
{
if(n==0&&m==0&&s==0) break;
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++)
scanf("%s",map[i]+1);
int x=1,y=s;
int temp=0,ans=0,cnt=0,flag=0;
while(check(x,y))
{
ans++;
//cout<<x<<" "<<y<<" "<<ans<<endl;
if(!vis[x][y]) vis[x][y]=1;
else if(vis[x][y]==1)
{
vis[x][y]=2;
cnt++;
if(!flag)
{
temp=ans;
flag=1;
}
}
else if(vis[x][y]==2) break;
if(map[x][y]=='N') x-=1;
else if(map[x][y]=='S') x+=1;
else if(map[x][y]=='W') y-=1;
else if(map[x][y]=='E') y+=1;
}
if(!check(x,y))
printf("%d step(s) to exit\n",ans);
else
printf("%d step(s) before a loop of %d step(s)\n",temp-cnt-1,cnt);
}
return 0;
}
3万+



被折叠的 条评论
为什么被折叠?



