UVa 227 Puzzle(模拟+字符串操作)

10 篇文章 0 订阅

题目传送门

 题意:有一个5*5的网格,其中恰好有一个格子是空的,其他格子各有一个字母。一共有4种指令:A,B,L,R,分别表示把空格上,下,左,右的相邻字母移到空格中。输入初始网格和指令序列(以数字0结束),输出指令执行完毕后的网格。如果有非法指令,应输出“This puzzle has no final configuration.”

题解:模拟一下就出结果了,处理输入输出比较麻烦。用了gets()函数,但是会多读入一个换行,很麻烦,加了getchar();以后神奇的消除了多读的换行。可以看看大神讲解的getchar()函数的功能(附上链接):https://blog.csdn.net/feixuedongji/article/details/78483900

代码如下:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
using namespace std;
#define io ios::sync_with_stdio(0),cin.tie(0)
#define ms(arr) memset(arr,0,sizeof(arr))
#define inf 0x3f3f3f
typedef long long ll;
const int mod=1e9+7;
const int maxn=3e3+7;
char s[10][10];
int main()
{
    int x,y,k=0,stop=0;
    char so[10050];
    memset(so,0,sizeof(so));
    while(gets(s[0]))
    {
        x=0,y=0;
        if(s[0][0]=='Z')
        {
            break;
        }
        gets(s[1]);
        gets(s[2]);
        gets(s[3]);
        gets(s[4]);
        for(int i=0;i<=4;i++)
        {
            for(int j=0;j<=4;j++)
            {
                if(s[i][j]==' ')
                {
                    x=i;
                    y=j;
                    break;
                }
            }
        }
        int len=0;
        while(cin>>so[len])
        {
            if(so[len]=='0')
                break;
            else
                len++;
        }
        so[len]=0;
        getchar();
        int ans=1;
        for(int i=0;so[i];i++)
        {
            if(so[i]=='A'&&x>=1)
            {
                swap(s[x][y],s[x-1][y]);
                x=x-1;
            }
            else if(so[i]=='B'&&x<=3)
            {
                swap(s[x][y],s[x+1][y]);
                x=x+1;
            }
            else if(so[i]=='L'&&y>=1)
            {
                swap(s[x][y],s[x][y-1]);
                y=y-1;
            }
            else if(so[i]=='R'&&y<=3)
            {
                swap(s[x][y],s[x][y+1]);
                y=y+1;
            }
            else
            {
                ans=0;
                break;
            }
        }
        if(k++)
            cout<<endl;
        cout<<"Puzzle #"<<k<<":"<<endl;
        if(ans)
        {
            for(int i=0;i<=4;i++)
            {
                for(int j=0;j<=4;j++)
                {
                    if(j)
                        cout<<" ";
                    cout<<s[i][j];
                }
                cout<<endl;
            }
        }
        else
            cout<<"This puzzle has no final configuration."<<endl;
    }
    return 0;
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值