poj2632Crashing Robots

http://poj.org/problem?id=2632

模拟算法:将整个过程完完整整的走一遍。题目怎么叙述的,程序就怎么运行。所以模拟题对算法设计的要求不高,但是需要大家选择最适当的数据结构来进行模拟,模拟题一般都很繁琐,所以信心和精心是必不可少的。

本题注意点挺多的,变量也很多,稍不注意就会错~~微笑也算是一道比较让人头疼的模拟题了。

#include <stdio.h>
#include <string.h>
int array[101][101];
int a,b;
int xf[4]={-1,0,1,0};
int yf[4]={0,1,0,-1};
struct Robot//自定义数据结构
{
    int x,y,d;
}robot[101];//every robot's current position and direction

int forward(int s,int t)//< robot #> < repeat> 
{
	int x,y,i;
	int d = robot[s].d;//取出当前方向
	x=robot[s].x;
	y=robot[s].y;//取出当前位置
	array[x][y]=0;//更新array[][]
	for(i=0;i<t;i++)
	{
		x =  x + xf[d];
		y =  y + yf[d];
		if(x<1 || x>a || y<1 || y>b)
		{
		    printf("Robot %d crashes into the wall\n",s);
		    return 1;
		}
		if(array[x][y])
		{
		    printf("Robot %d crashes into robot %d\n",s,array[x][y]);
		    return 1;
		}
	}
	robot[s].x=x;//更新当前所在位置
	robot[s].y=y;
	array[x][y]=s;//更新array[][]
	return 0;
}

int action(int s,char dir,int t)//instruction:< robot #> < action> < repeat> 
{
    //对于'F'指令,需判断前进是否出界和前进的位置是否已有机器人
    //对于'L'和'R'转向指令,只需修改机器人的方向值,注意同一方向转四次等于没转
	switch (dir)
	{
		case 'F':return forward(s,t);
		case 'L':robot[s].d=(robot[s].d-t%4+4)%4;break;
		case 'R':robot[s].d=(robot[s].d+t%4)%4;break;
	}
	return 0;
}

int main()
{
	int k,n,m,xi,yi,i,j,s,t;
	int f=0;
	char dir;
	scanf("%d",&k);//test numbers
	for(i=0;i<k;i++)
	{
		memset(array,0,sizeof(array));
		memset(robot,0,sizeof(robot));
		scanf("%d %d",&a,&b);// the size of the warehouse in meters
		scanf("%d %d",&n,&m);//the numbers of robots and instructions respectively
		for(j=0;j<n;j++)//n个机器人
		{
			scanf("%d %d %c",&xi,&yi,&dir);//the starting position and direction of each robot
			array[xi][yi]=j+1;//array[xi][yj]代表(xi,yj)位置处的robot编号,没有则为0
			robot[j+1].x=xi;
			robot[j+1].y=yi;//init current position
			switch(dir)//init current direction
			{
				case 'W':robot[j+1].d=0;break;
				case 'N':robot[j+1].d=1;break;
				case 'E':robot[j+1].d=2;break;
				case 'S':robot[j+1].d=3;break;
				default:robot[j+1].d=-1;
			}
		}
		f=0;
		for(j=0;j<m;j++)//m条指令
		{
			scanf("%d %c %d",&s,&dir,&t);//instruction:< robot #> < action> < repeat> 
			if(f==0)
			{
			    f=action(s,dir,t);//action只有两种可能,发生碰撞返回1,无碰撞返回0
			}
		}
		if(f==0)
		    printf("OK\n");
	}
	return 0;
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值