谜题(Puzzle,ACM/ICPC World Finals 1993,UVa227)

题目

在这里插入图片描述

思路

这一道题乍一看好像有一定难度,其实仔细分析下来只是一道很简单的数组之间元素交换的题目,就是过程复杂了一点。

  • 输入字符串每次输入就判断是否遇到0,如果遇到了就停止输入。输入的同时保存一个输入位数的指针n
  • 进行n次循环,每次读取输入字符串中一个字符,判断是哪种类型并进行相应操作。如果遇到非法输入就跳出循环。
  • 交换操作先找到空格所在位置(这道题空格用#代替比较清楚)用x,y保存位置信息,之后就是正常的交换,每次交换过后注意空格的位置改变了,所以x,y的数值也要做出相应改变
  • 在这题我还加了一个判断是否到边界的环节,如果到边界就输出到边界。

代码

#include <iostream>

using namespace std;

int main()
{
    char a[5][5]={'T','R','G','S','J','X','D','O','K','I','M','#','V','L','N','W','P','A','B','E','U','Q','H','C','F'};
    char b[1000];
    int n,x,y,c;
    char p,temp;
    n=c=0;
    for(int i=0;i<1000;i++)
    {
        n++;
        cin>>b[i];
        if(b[i]=='0')
        {
            n--;
            break;
        }
    }
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
        {
            if(a[i][j]=='#')
            {
                x=i;
                y=j;
            }
        }
    for(int i=0;i<n;i++)
    {
        p=b[i];
        if(p=='A')
        {
            if(x-1>=0)
            {
                temp=a[x-1][y];
                a[x-1][y]=a[x][y];
                a[x][y]=temp;
                x--;
            }
            else cout<<"This puzzle has reached the top"<<endl;
        }
        else if(p=='R')
        {
            if(y+1<5)
            {
                temp=a[x][y+1];
                a[x][y+1]=a[x][y];
                a[x][y]=temp;
                y++;
            }
            else cout<<"This puzzle has reached the rightmost"<<endl;
        }
        else if(p=='B')
        {
            if(x+1<5)
            {
                temp=a[x+1][y];
                a[x+1][y]=a[x][y];
                a[x][y]=temp;
                x++;
            }
            else cout<<"This puzzle has reached the bottom"<<endl;
        }
        else if(p=='L')
        {
            if(y-1>=0)
            {
                temp=a[x][y-1];
                a[x][y-1]=a[x][y];
                a[x][y]=temp;
                y--;
            }
            else cout<<"This puzzle has reached the leftmost"<<endl;
        }
        else
        {
            cout<<"This puzzle has no final configuration";
            c=1;
            break;

        }
    }
    if(c==0)
    {
        for(int i=0;i<5;i++)
        {
            for(int j=0;j<5;j++)
                cout<<a[i][j];
            cout<<endl;
        }
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值