joj 1034: Worm Turns

本文介绍了一种模拟贪吃蛇游戏的算法实现。通过定义结构体来表示蛇身上的每个方块,并使用双向链表来存储蛇的身体。利用C++语言进行编程,实现了蛇在移动过程中遇到边界、自身身体时的游戏结束条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[url]http://acm.jlu.edu.cn/joj/showproblem.php?pid=1034[/url]
这道题类似于贪吃蛇游戏,让你模拟Worm移动,看第几步跑出board,第几步跑到自己身上,全部完成。所以算法就是模拟。

#include<iostream>
#include<list>
#include<string>
using namespace std;

struct Square{
int x;
int y;
};

const int ROWS = 51;
const int COLS = 51;

list<Square> worm;

void init_worm(){
worm.clear();
int i = 25;
int j = 11;
for(; j <= 30; j++){
Square s;
s.x = i;
s.y = j;
worm.push_front(s);
}
}

bool in_bound(int i,int j){
return i >= 1 && i < ROWS-1 && j >= 1 && j <= COLS-1;
}

bool run_into_self(int x, int y){
list<Square>::iterator it = worm.begin();
list<Square>::reverse_iterator rit = worm.rbegin();

if(rit->x == x && rit->y == y)//deal with the tail specially
return false;

for(; it != worm.end(); it++){
if(it->x == x && it->y == y){
return true;
}
}
return false;
}

bool move(int i,int j,int current_step){
Square head = worm.front();
int x = head.x + i;
int y = head.y + j;

if( !in_bound(x,y) ){
cout << "The worm ran off the board on move " << current_step << "." << endl;
return false;
}else if( run_into_self(x,y) ){
cout << "The worm ran into itself on move " << current_step << "." << endl;
return false;
}else{
head.x = x;
head.y = y;
worm.push_front(head);
worm.pop_back();
return true;
}
}


int main(){
int move_steps;
while(cin >> move_steps,move_steps){
init_worm();
int i;
bool flag;
string moves;
cin >> moves;
for(i = 1; i <= move_steps; i++){
flag = true;
char ch = moves[i-1];
switch(ch){
case 'E':
if(!move(0,1,i))
flag = false;
break;
case 'W':
if(!move(0,-1,i))
flag = false;
break;
case 'N':
if(!move(-1,0,i))
flag = false;
break;
case 'S':
if(!move(1,0,i))
flag = false;
break;
defalut:
break;
}

if(!flag)
break;

}
if(i == move_steps + 1)
cout << "The worm successfully made all " << move_steps << " moves." << endl;
}
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值