第三章:UVa227 解题报告

UVa227 解题报告

这是一道final题,但是没有什么算法难度。只需要模拟即可,但是如果用std::getline(),配合string输出会WA,具体原因我也没有探究清楚,如果改为gets(),配合char数组就没有问题。注意不合法操作的边界判断。
以下是代码(可直接AC):

#include <iostream>
#include <string>
#include <cstring>
#include <memory.h>
using std::cin;
using std::cout;
using std::string;

char map[6][7];
char line[100000];
int move(int &x,int &y,char command);

int main()
{
    int i=0,j=0,k=0,l=0,ox=0,oy=0;
    int solved=1,cnt=0;
    while(gets(line)&&line[0]!='Z')
    {
        if(i<5)//前5行是map
        {
            memcpy(map[i],line,5*sizeof(char));
            if(i==4)
            {
                for(j=0;j<5;j++)
                    for(k=0;k<5;k++)
                        if(map[j][k]==' ')
                        {
                            ox=j;
                            oy=k;
                        }

            }
            i++;
        }else{//后K行是命令
            for(j=0;j<strlen(line);j++)
                if(line[j]!='0')
                {
                    if(!move(ox,oy,line[j]))
                        solved=0;
                }else{//打印结果
                    if(cnt++>=1)//不是第一组前面就多空一行
                        cout<<'\n';
                    cout<<"Puzzle #"<<cnt<<":\n";
                    if(solved)
                        for(k=0;k<5;k++)
                        {   
                            cout<<map[k][0];
                            for(l=1;l<5;l++)
                                    cout<<' '<<map[k][l];
                            cout<<'\n';
                        }
                    else
                        cout<<"This puzzle has no final configuration.\n";
                    i=0;//一组读完重置参数
                    solved=1;
                }
        }
    }
    return 0;
}

int move(int &x,int &y,char command)//移动空格的函数
{
    char temp;
    switch(command)
    {
        case 'A':
            if(x-1<0)
                return 0;
            temp=map[x-1][y];
            map[x-1][y]=map[x][y];
            map[x][y]=temp;
            x--;
            break;
        case 'B':
            if(x+1>4)
                return 0;
            temp=map[x+1][y];
            map[x+1][y]=map[x][y];
            map[x][y]=temp;
            x++;
            break;
        case 'R':
            if(y+1>4)
                return 0;
            temp=map[x][y+1];
            map[x][y+1]=map[x][y];
            map[x][y]=temp;
            y++;
            break;
        case 'L':
            if(y-1<0)
                return 0;
            temp=map[x][y-1];
            map[x][y-1]=map[x][y];
            map[x][y]=temp;
            y--;
            break;
    }
    return 1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值