UVA-227 Puzzle

来源:互联网 发布:win10优化 编辑:程序博客网 时间:2024/04/29 17:30

原题链接见> 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;    }
0 0
原创粉丝点击