您的位置:首页 > 其它

ZOJ Problem Set - 1056 The Worm Turns

2011-10-22 14:28 387 查看
一道蠕虫模拟题~~很简单。考虑头和尾的变化即可。用map记录整个虫的形状,然后看看头是不是碰撞到虫身或墙壁。虫尾是跟着虫头走的。

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
bool flag ;
struct Node
{
int x,y;
};
Node tail,head;
bool map[50][50];
void init()
{
int  i;
memset(map,0,sizeof(map));
for(i = 10;i < 29;i ++)
map[24][i] = 1;
head.x = 24;head.y = 29;
tail.x = 24;tail.y = 10;
}
void judge(int i)
{
if(head.x < 0||head.x >= 50||head.y<0||head.y>=50)
{
cout<<"The worm ran off the board on move "<<i<<"."<<endl;
flag = 0;
return ;
}
if(map[head.x][head.y] == 1)
{
cout<<"The worm ran into itself on move "<<i<<"."<<endl;
flag = 0;
return ;
}

}
int main()
{
int i,j,len;
string str;
//freopen("a.txt","r",stdin);
while(cin>>len&&len !=0)
{
cin>>str;
init();
j = 0;
for(i = 0;i < len;i ++)
{
switch(str[i])
{
case 'S':map[head.x][head.y] = 1;head.x ++;
map[tail.x][tail.y] = 0;
if(i < 19) tail.y ++;
else
{
switch(str[j++])
{
case 'N': tail.x --;break;
case 'S': tail.x ++;break;
case 'E': tail.y ++;break;
case 'W': tail.y --;break;
}
}
break;
case 'N':map[head.x][head.y] = 1;head.x --;
map[tail.x][tail.y] = 0;
if(i < 19) tail.y ++;
else
{
switch(str[j++])
{
case 'N': tail.x --;break;
case 'S': tail.x ++;break;
case 'E': tail.y ++;break;
case 'W': tail.y --;break;
}
}
break;
case 'E':map[head.x][head.y] = 1;head.y ++;
map[tail.x][tail.y] = 0;
if(i < 19) tail.y ++;
else
{
switch(str[j++])
{
case 'N': tail.x --;break;
case 'S': tail.x ++;break;
case 'E': tail.y ++;break;
case 'W': tail.y --;break;
}
}
break;
case 'W':map[head.x][head.y] = 1;head.y --;
map[tail.x][tail.y] = 0;
if(i < 19) tail.y ++;
else
{
switch(str[j++])
{
case 'N': tail.x --;break;
case 'S': tail.x ++;break;
case 'E': tail.y ++;break;
case 'W': tail.y --;break;
}
}
break;
}
flag = 1;
judge(i+1);
//cout<<i+1<<endl;
/*for(int k = 24;k < 26;k ++){
for( j = 0; j < 50;j ++)
cout<<map[k][j];
cout<<endl;
}*/
if(flag == 0) break;

}
if(flag) cout<<"The worm successfully made all "<<len<<" moves."<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: