您的位置:首页 > 其它

UVa-227 - Puzzle

2015-02-14 03:36 381 查看
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
void f(char a,int &xx,int &yy)
{
if(a=='A') xx=-1,yy=0;
else if(a=='B') xx=1,yy=0;
else if(a=='R') xx=0,yy=1;
else if(a=='L') xx=0,yy=-1;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
char a[10][10]={};
int cnt=0;
while(gets(a[1]+1)&&a[1][1]!='Z')
{
++cnt;
if(cnt>1) printf("\n");
printf("Puzzle #%d:\n",cnt);
for(int i=2;i<=5;i++)
gets(a[i]+1);
int x,y;
for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
if(a[i][j]==' ')
x=i,y=j;
char b[100]={};
cin.getline(b,100,'0');
getchar();
bool flag=1;
for(int i=0;b[i]!='\0';i++)
{
if(b[i]=='\n') continue;
int xx=0,yy=0;
f(b[i],xx,yy);
if(a[x+xx][y+yy]=='\0')
{
flag=0;
printf("This puzzle has no final configuration.\n");
break;
}
char t=a[x+xx][y+yy];
a[x+xx][y+yy]=a[x][y];
a[x][y]=t;
x=x+xx,y=y+yy;
}
if(flag)
{
for(int i=1;i<=5;i++)
{
printf("%c",a[i][1]);
for(int j=2;j<=5;j++)
printf(" %c",a[i][j]);
printf("\n");
}
}
memset(a,0,sizeof(a));
}
}

上面的读取操作指令的方式是先全部存下来,下面是另外一种方法–一个一个字符地读。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
void f(char a,int &xx,int &yy)
{
if(a=='A') xx=-1,yy=0;
else if(a=='B') xx=1,yy=0;
else if(a=='R') xx=0,yy=1;
else if(a=='L') xx=0,yy=-1;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
char a[10][10]={};
int cnt=0;
while(gets(a[1]+1)&&a[1][1]!='Z')
{
++cnt;
if(cnt>1) printf("\n");
printf("Puzzle #%d:\n",cnt);
for(int i=2;i<=5;i++)
gets(a[i]+1);
int x,y;
for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
if(a[i][j]==' ')
x=i,y=j;
char b;
while(1)
{
b=getchar();
if(b=='0') break;
else if(b=='\n') continue;
int xx=0,yy=0;
f(b,xx,yy);
if(a[x+xx][y+yy]=='\0')
{
printf("This puzzle has no final configuration.\n");
break;
}
char t=a[x+xx][y+yy];
a[x+xx][y+yy]=a[x][y];
a[x][y]=t;
x=x+xx,y=y+yy;
}
if(b=='0')
{
for(int i=1;i<=5;i++)
{
printf("%c",a[i][1]);
for(int j=2;j<=5;j++)
printf(" %c",a[i][j]);
printf("\n");
}
}
else while(getchar()!='0'){}
getchar();
memset(a,0,sizeof(a));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: