poj2632--模拟

/** \brief poj 2632
 *
 * \param date 2014/8/3
 * \param state AC
 * \return memory 776k time 16ms
 *
 */

#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

const int MAXN=101;
int Map[MAXN][MAXN];

int A,B;
int N,M;
int xf[4]={-1,0,1,0};
int yf[4]={0,1,0,-1};

struct Robot
{
    int x;
    int y;
    //char dir;
    int dir;
    //int num;
};

Robot robots[MAXN];

//将方向数字化
int charDir2Int(char cDir)
{
    switch(cDir)
    {
    case 'E':
        return 2;
    case 'S':
        return 3;
    case 'W':
        return 0;
    case 'N':
        return 1;
    };
}

//模拟搜索
bool Forward(int s,int t)
{
    int x,y;
    int d=robots[s].dir;
    x=robots[s].x;
    y=robots[s].y;
    Map[x][y]=0;//走过为0
    for(int i=0;i<t;i++)
    {
        x=x+xf[d];
        y=y+yf[d];
        //边界 -- wall判断
        if(x<1 || x>A || y<1 || y>B)
        {
            cout<<"Robot "<<s<<" crashes into the wall"<<endl;
            return true;
        }
        if(Map[x][y])
        {
            cout<<"Robot "<<s<<" crashes into robot "<<Map[x][y]<<endl;
            return true;
        }
    }
    robots[s].x=x;
    robots[s].y=y;
    Map[x][y]=s;//到达新点,赋上序号
    return false;
}

//指令--行动
bool Action(int s,char Dir,int t)
{
    switch(Dir)
    {
    case 'F':
        return Forward(s,t);
    case 'L':
        robots[s].dir=(robots[s].dir-t%4+4)%4;
        break;
    case 'R':
        robots[s].dir=(robots[s].dir+t%4)%4;
        break;
    }
    return false;
}

int main()
{
    //cout << "Hello world!" << endl;
    freopen("input.txt","r",stdin);
    int K;
    cin>>K;
    for(int k=0;k<K;k++)
    {
        memset(Map,0,sizeof(Map));
        cin>>A>>B;
        cin>>N>>M;
        for(int i=1;i<=N;i++)
        {
            int x,y;
            char dir;
            cin>>x>>y>>dir;
            robots[i].x=x;
            robots[i].y=y;
            robots[i].dir=charDir2Int(dir);
            //robots[i].num=i;
            Map[x][y]=i;
        }
        bool f=false;//it means that OK
        for(int j=0;j<M;j++)
        {
            int num,repeat;
            char op;
            cin>>num>>op>>repeat;
            //
            if(!f)f=Action(num,op,repeat);
        }
        if(!f)cout<<"OK"<<endl;
    }
    return 0;
}


参考:http://blog.csdn.net/tiantangrenjian/article/details/6827710

模拟算法:根据题目所述移动步骤逐步进行,利用数组array[i][j]代表(i,j)位置处的robot编号,没有则为0.

利用robot结构体记录下每个机器人当前的位置和方向。

对于'F'指令,需判断前进是否出界和前进的位置是否已有机器人。

对于'L'和'R'转向指令,只需修改机器人的方向值,注意同一方向转四次等于没转。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值