题意:有一个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;
}