模拟类的题,虽然看着很简单,但是因为这个题描述有点模糊,而且格式很多,又涉及getchar,fgets等函数,所以 写起来很费劲,我模仿别人的代码写的还废了我一天功夫,超累。主要就是在写c数组的时候没有进行初始化的操作,所以前面的操作序列影响到了后面的操作序列数组,导致一直wa,所以说一定要养成初始化数组的好习惯啊。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
using namespace std;
/*void swap(char &c1, char &c2)
{
char c3;
c3 = c1;
c1 = c2;
c2 = c3;
}*/
int main()
{
char ch[10][10];//虽燃是5*5的格子,但还是开大一点好,避免越界出现错误。
int counter = 0;
while(fgets(ch[0], 7, stdin))//这个地方注意是下一次重新开始时,判断是否是结束.
{
if(ch[0][0] == 'Z')
{
break;
}
for(int i = 1; i < 5; ++i)
{
fgets(ch[i], 7, stdin);
}
int m, n;
for(int i = 0; i < 5; ++i)
{
for(int j = 0; j < 5; ++j)
{
if(ch[i][j] == ' ')
{
m = i;n = j;
//cout << m << " " << n <<endl;
break;
}
}
}
char c[105];
memset(c, 0, sizeof(char)*105);
int j = 0;
char s;
while((s = getchar()) != '0')
{
if(s == 'A' || s == 'R' || s == 'B' || s == 'L')
{
c[j] = s;
++j;
//cout << "c[]"<< c[j];
}
}
getchar();
int m1,n1;
m1 = m;n1 = n;
bool flat = true;
for(int i = 0; i < strlen(c); ++i)
{
switch(c[i])
{
case 'A':
m1 = m1 -1;break;
case 'B':
m1 = m1 + 1;break;
case 'L':
n1 = n1 - 1;break;
case 'R':
n1 = n1 + 1;break;
default:
break;
}
if(m1 >4 || m1 < 0 || n1 > 4 || n1 < 0)
{
flat = false;
break;
}
if(flat)
{
swap(ch[m][n], ch[m1][n1]);
m = m1; n = n1;
//cout << "---------";
}
}
//getchar();//输出0后有一个换行。
if(counter++)
{
cout << endl;
}
if(flat)
{
printf("Puzzle #%d:\n", counter);
for(int i1 = 0; i1 < 5; ++i1)
{
int j1;
for(j1 = 0; j1 < 4; ++j1)
{
printf("%c ", ch[i1][j1]);
}
printf("%c\n", ch[i1][j1]);
}
}
else
{
printf("Puzzle #%d:\n", counter);
printf("%s\n", "This puzzle has no final configuration.");
}
}
return 0;
}
代码参考
https://blog.csdn.net/lecholin/article/details/70147512
他那里关于格式问题已经写的很全面了。