题目链接:http://acm.tju.edu.cn/toj/showp1191.html
题目大意:模拟贪吃蛇移动 长度为20
思路:呵呵 有点意思 发现南北方向变了都能AC 但我还是按正常思维处理南北方向的变化好了
代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
using namespace std;
int main()
{
int n,i,j,res,flag[101];
char str[101];
bool a[51][51];
while(cin>>n)
{
if(n==0)break;
//初始化棋盘
for(i=0;i<=50;i++)
for(j=0;j<=50;j++)
a[i][j]=0;
//初始化worm位置
for(i=10;i<=29;i++)
a[24][i]=1;
//初始化时除了head外的另外19块作为尾巴时只能向东走 这里要结合游戏场景好好理解
for(i=0;i<19;i++)
flag[i]=4;
cin>>str;
int tailx=24,taily=10; //尾部坐标
int headx=24,heady=29; //头部坐标
for(i=0;i<n;i++)
{
if(str[i]=='E') //往东走 只用管头部和尾部的坐标变化情况即可
{
a[tailx][taily]=0; //因为尾巴移动,所以首先尾部变为0
if(a[headx][heady+1]==1) //如果头部移动到已经有方块的位置 表示吃到自己了
{cout<<"The worm ran into itself on move "<<i+1<<"."<<endl;break;}
heady=heady+1; //否则头部向东前移
a[headx][heady]=1; //标记移动到的位置
if(flag[i]==4)taily=taily+1; //记录尾部坐标变化情况
if(flag[i]==3)tailx=tailx-1;
if(flag[i]==2)taily=taily-1;
if(flag[i]==1)tailx=tailx+1;
flag[i+19]=4; //这句是关键 表示头部移动方向对19步后尾部的影响 你想想游戏里是不是这样
}
if(str[i]=='S')
{
a[tailx][taily]=0;
if(a[headx+1][heady]==1)
{cout<<"The worm ran into itself on move "<<i+1<<"."<<endl;break;}
headx=headx+1;
a[headx][heady]=1;
if(flag[i]==4)taily=taily+1;
if(flag[i]==3)tailx=tailx-1;
if(flag[i]==2)taily=taily-1;
if(flag[i]==1)tailx=tailx+1;
flag[i+19]=1;
}
if(str[i]=='W')
{
a[tailx][taily]=0;
if(a[headx][heady-1]==1)
{cout<<"The worm ran into itself on move "<<i+1<<"."<<endl;break;}
heady=heady-1;
a[headx][heady]=1;
if(flag[i]==4)taily=taily+1;
if(flag[i]==3)tailx=tailx-1;
if(flag[i]==2)taily=taily-1;
if(flag[i]==1)tailx=tailx+1;
flag[i+19]=2;
}
if(str[i]=='N')
{
a[tailx][taily]=0;
if(a[headx-1][heady]==1)
{cout<<"The worm ran into itself on move "<<i+1<<"."<<endl;break;}
headx=headx-1;
a[headx][heady]=1;
if(flag[i]==4)taily=taily+1;
if(flag[i]==3)tailx=tailx-1;
if(flag[i]==2)taily=taily-1;
if(flag[i]==1)tailx=tailx+1;
flag[i+19]=3;
}
if(headx>=50||heady>=50||headx<0||heady<0)
{cout<<"The worm ran off the board on move "<<i+1<<"."<<endl;break;}
}
if(i==n)cout<<"The worm successfully made all "<<n<<" moves."<<endl;
}
return 0;
}