UVa- 227 - Puzzle:单纯模拟 & 数据(字符数组)读入练习

本文介绍了一种使用C++实现的迷宫游戏算法,通过解析指令来移动游戏中的空位,实现迷宫状态的变化。文章提供了完整的源代码,并讨论了如何通过switch语句优化Move函数以减少代码量。

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


Move函数写得太菜了···一个switch可以减少很多代码量···

单纯模拟:代码思路清晰

#define LOCAL
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;

char Puzzle[5][7];
int X,Y;
string Inst;
int Round=0;
int NoFinal=0;

void Move(){
    for(int i=0; i<Inst.length(); i++){
        if(Inst[i]=='A') {
                if(X-1<0) {
                        NoFinal=1; return;
                }
                swap(Puzzle[X-1][Y],Puzzle[X][Y]);
                X--;
        }
        if(Inst[i]=='B') {
                if(X+1>4) {
                        NoFinal=1; return;
                }
                swap(Puzzle[X+1][Y],Puzzle[X][Y]);
                X++;
        }
        if(Inst[i]=='L') {
                if(Y-1<0){
                        NoFinal=1; return;
                }
                swap(Puzzle[X][Y-1],Puzzle[X][Y]);
                Y--;
        }
        if(Inst[i]=='R') {
                if(Y+1>4) {
                        NoFinal=1; return;
                }
                swap(Puzzle[X][Y+1],Puzzle[X][Y]);
                Y++;
        }
    }
}

void Display(){
    if(Round++) printf("\n");
    printf("Puzzle #%d:\n",Round);
    if(NoFinal){
        printf("This puzzle has no final configuration.\n");
        return ;
    }
    for(int i=0; i<5; i++){
        for(int j=0; j<5; j++){
            if(j)
                printf(" %c",Puzzle[i][j]);
            else
                printf("%c",Puzzle[i][j]);
        }
        printf("\n");
    }
}

int main()
{
#ifdef LOCAL
    freopen("in1.txt","r",stdin);
#endif

    while(1)
    {
        NoFinal=0;
        int End=0;
        for(int i=0; i<5; i++)
        {
            for(int j=0; j<6; j++){
                Puzzle[i][j]=getchar();
                if(Puzzle[i][j]==' '){
                    X=i; Y=j;
                }
                if(Puzzle[i][j]=='Z'){
                    End=1; break;
                }
            }
            if(End) break;
        }//for
        if(End) return 0;
        Inst=""; char C;
        while( (C=getchar())!='0' ){
            if(C=='\n') continue;
            Inst+=C;
        }
        getchar();
        Move();
        Display();
    }//while
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值