链接 : http://acm.tju.edu.cn/toj/showp3984.html
有问题联系:QQ 970026607
题目大意: 贪吃蛇的游戏,吃了就变长,判断会不会随着时间的移动(操作),撞到墙,或者自己。
我的解法是用了一个 vector 保存之前的状态,len 表示蛇的长度,嗯,就我来代码来说,只要判断 vector[i-len+2…..i-2]之间状态就可以判断是否会撞到自己。
容易犯下的错误
这里一开始
if(nx<=0||nx>h || ny<=0||ny>w){
printf("The snake crash itself after %d operations.\n",i+1);
goto loop1;
}
被我写成
if(nx<=0&&nx>=h && ny<=0&&ny>=w){
printf("The snake crash itself after %d operations.\n",i+1);
goto loop1;
}
还有就是吃过的食物 map[nx][ny] 没有清除标记,
导致吃了再吃。
Ac 代码如下 :
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
using namespace std;
typedef long long ll;
struct state{
int x,y;
state(int x1,int y1): x(x1),y(y1){}
state(){}
}st;
bool map1[22][22];
char op[200];
vector<state> v;
int main(){
//freopen("F:\\123.txt","r",stdin);
int n,w,h,x,y;
while(scanf("%d%d%d%d%d",&n,&w,&h,&x,&y)!=EOF){
if(n||w||h||x||y){
memset(map1,0,sizeof(map1));
int ux,uy;
for(int i=0;i<n;i++)
{
scanf("%d%d",&ux,&uy);
map1[ux][uy]=true;
}
int len=1;
v.clear();
scanf("%s",op);
int num=strlen(op);
v.push_back(state(x,y));
int nx,ny;
for(int i=0;i<num;i++){
if(op[i]=='U'){
nx=v[i].x-1,ny=v[i].y;
if(nx<=0||nx>h || ny<=0||ny>w){
printf("The snake crash itself after %d operations.\n",i+1);
goto loop1;
}
if(map1[nx][ny]) {
map1[nx][ny]=false;
len++;
}
for(int j=i-len+2;j<=i-1;j++){
if((nx==v[j].x&&ny==v[j].y)){
printf("The snake crash itself after %d operations.\n",i+1);
goto loop1;
}
}
v.push_back(state(nx,ny));
}else if(op[i]=='D'){
nx=v[i].x+1,ny=v[i].y;
if(nx<=0||nx>h || ny<=0||ny>w){
printf("The snake crash itself after %d operations.\n",i+1);
goto loop1;
}
if(map1[nx][ny]) {
map1[nx][ny]=false;
len++;
}
for(int j=i-len+2;j<=i-1;j++){
if((nx==v[j].x&&ny==v[j].y)){
printf("The snake crash itself after %d operations.\n",i+1);
goto loop1;
}
}
v.push_back(state(nx,ny));
}else if(op[i]=='L'){
nx=v[i].x,ny=v[i].y-1;
if(nx<=0||nx>h || ny<=0||ny>w){
printf("The snake crash itself after %d operations.\n",i+1);
goto loop1;
}
if(map1[nx][ny]) {
map1[nx][ny]=false;
len++;
}
for(int j=i-len+2;j<=i-1;j++){
if((nx==v[j].x&&ny==v[j].y)){
printf("The snake crash itself after %d operations.\n",i+1);
goto loop1;
}
}
v.push_back(state(nx,ny));
}else {
nx=v[i].x,ny=v[i].y+1;
if(nx<=0||nx>h || ny<=0||ny>w){
printf("The snake crash itself after %d operations.\n",i+1);
goto loop1;
}
if(map1[nx][ny]) {
map1[nx][ny]=false;
len++;
}
for(int j=i-len+2;j<=i-1;j++){
if((nx==v[j].x&&ny==v[j].y)){
printf("The snake crash itself after %d operations.\n",i+1);
goto loop1;
}
}
v.push_back(state(nx,ny));
}
}
printf("The snake is %d unit long after A's operation.\n",len);
loop1: v.clear();
}else{
break;
}
}
return 0;
}