UVA-227 Puzzle

原题链接见> https://vjudge.net/problem/UVA-227

题意分析:

有一个5*5的网格,只有一个格子是空格,其余的都是字母。
4个指令 A,B,L,R,分别代表向上向下向左向右。
输出执行完后的网格内的情况。
若有越界则单独输出、

代码:

#include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    int main()
    {
        char maps[6][6];   //习惯性的用大一点的数组,没什么必要
        char cmd[1000];    //记录指令
        int count=0;
        while(gets(maps[0]))
        {   
            if(maps[0][0]=='Z')
            break;

            for(int i=1;i<5;i++)
            gets(maps[i]);

            int len;
            for(int i=0;i>=0;i++){
                cin>>cmd[i];
                if(cmd[i]=='0'){
                    len=i;
                    cmd[i+1]='\0';
                    break;
                }
            }
            if(count++)
            cout<<endl; 
            cout<<"Puzzle #"<<count<<":"<<endl;
            bool flag=false;

            int x,y;
            for(int i=0;i<5;i++)
                for(int j=0;j<5;j++)
                if(maps[i][j]==' '){
                    x=i;y=j;
                    break;
                }
            getchar();//因为cin不读回车,所以需要把一个回车读到,在这里卡了好久T_T
            int x_1=x,y_1=y;//另外声明间接变量比直接判断更方便(因为不用考虑数组真的越界和其他问题)
            for(int i=0;i<len;i++){

                if(cmd[i]=='A')
                    x_1=x-1; 
                else if(cmd[i]=='B')
                    x_1=x+1; 
                else if(cmd[i]=='L')
                    y_1=y-1;
                else if(cmd[i]=='R')
                    y_1=y+1;

                if(x_1<0||x_1>=5||y_1<0||y_1>=5){
                    flag=true;
                    break;
                }
                swap(maps[x][y],maps[x_1][y_1]);    
                x=x_1;y=y_1;
            }

            if(flag)
            cout<<"This puzzle has no final configuration."<<endl;
            else{
                for(int i=0;i<5;i++){
                    for(int j=0;j<5;j++){
                        if(j)
                        cout<<" ";
                        cout<<maps[i][j];
                    }
                    cout<<endl;
                }
            }

            memset(maps,0,sizeof(maps));
        }
        return 0;
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值