背景:这道题不涉及算法,只是普通的模拟。
思路:用结构体存储一个机器人的横坐标,纵坐标,还有他的方向,我在方向这个问题上运用了一点小技巧,那就是用0,1,2,3分别代表N,W,E,S这样对于处理L和R就非常的方便了。最主要的就是在处理F命令中既要注意机器人在移动过程中遇到其他机器人,又要注意机器人是否越界,在这方面,可以运用一个数组模拟出整个工厂,每个位置初始化为0,有机器人的位置设置为该机器人的编号,这样就能够很简单的处理F命令了。
注意:有一点需要注意,就是已经有输出的时候,不能够直接退出,要等到把这组数据输完之后才能够退出,否则会严重影响到以后数据的处理。
学习:结构体的简单运用。
#include <iostream>
#include <cstring>
using namespace std;
int whouse[105][105],A,B;
struct robot
{
int x,y,fangxiang;
}r[101];
int move_E(int ra,int step)
{
int x1=r[ra].x,y1=r[ra].y;
whouse[x1][y1]=0;
if(r[ra].fangxiang==0)
{
for(int i=1;i<=step;i++)
{
if(y1+step>B)
{
cout<<"Robot "<<ra<<" crashes into the wall"<<endl;
return 0;
}
if(whouse[x1][y1+i]!=0)
{
cout<<"Robot "<<ra<<" crashes into robot "<<whouse[x1][y1+i]<<endl;
return 0;
}
}
whouse[x1][y1+step]=ra;
r[ra].y=y1+step;
}
else if(r[ra].fangxiang==1)
{
for(int i=1;i<=step;i++)
{
if(x1-step<=0)
{
cout<<"Robot "<<ra<<" crashes into the wall"<<endl;
return 0;
}
if(whouse[x1-i][y1]!=0)
{
cout<<"Robot "<<ra<<" crashes into robot "<<whouse[x1-i][y1]<<endl;
return 0;
}
}
whouse[x1-step][y1]=ra;
r[ra].x=x1-step;
}
else if(r[ra].fangxiang==2)
{
for(int i=1;i<=step;i++)
{
if(y1-i<=0)
{
cout<<"Robot "<<ra<<" crashes into the wall"<<endl;
return 0;
}
if(whouse[x1][y1-i]!=0)
{
cout<<"Robot "<<ra<<" crashes into robot "<<whouse[x1][y1-i]<<endl;
return 0;
}
}
whouse[x1][y1-step]=ra;
r[ra].y=y1-step;
}
else
{
for(int i=1;i<=step;i++)
{
if(x1+i>A)
{
cout<<"Robot "<<ra<<" crashes into the wall"<<endl;
return 0;
}
if(whouse[x1+i][y1]!=0)
{
cout<<"Robot "<<ra<<" crashes into robot "<<whouse[x1+i][y1]<<endl;
return 0;
}
}
whouse[x1+step][y1]=ra;
r[ra].x=x1+step;
}
return 1;
}
int main(void)
{
int K;
cin>>K;
while(K--)
{
int N,M,ok=1;
cin>>A>>B>>N>>M;
memset(whouse,0,sizeof(whouse));
for(int i=1;i<=N;i++)
{
char ch;
cin>>r[i].x>>r[i].y>>ch;
if(ch=='N') r[i].fangxiang=0;
else if(ch=='W') r[i].fangxiang=1;
else if(ch=='S') r[i].fangxiang=2;
else r[i].fangxiang=3;
whouse[r[i].x][r[i].y]=i;
}
while(M--)
{
int ra,step;
char order;
cin>>ra>>order>>step;
if(!ok) continue;
if(order=='L') r[ra].fangxiang=(r[ra].fangxiang+step)%4;
else if(order=='R') r[ra].fangxiang=(r[ra].fangxiang+4-step%4)%4;
else ok=move_E(ra,step);
}
if(ok) cout<<"OK"<<endl;
}
return 0;
}