题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=163(因为格式的原因 贴过来看起来很不舒服 所以直接发链接了,中文版可参考紫书57页习题3-5)
思路很清晰就是简单地模拟一下,根据它的指令来做就好了。输入注意一下。
AC代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
char c[5][5];
int x, y, ok, flag, cnt;
int main()
{
cnt = flag = 0;
while(gets(c[0]))
{
//cout << "c[0][0]=" << c[0][0] << endl;
if(c[0][0] == 'Z') break;
for(int i = 1; i < 5; ++i)
gets(c[i]);
//if(i) getchar();
for(int i = 0; i < 5; ++i)
for(int j = 0; j < 5; ++j)
{
//if(i == 0 && j == 0) continue;
//scanf("%c",&c[i][j]);
if(c[i][j]==' ')
{
x = i;
y = j;
break;
}
}
/*for(int i = 0; i < 5; ++i)
cout << c[i] << endl;*/
char ch;
ok = 1;
while(1)
{
ch = getchar();
if(ch == '0') break;
if(ok)
{
if(ch == 'L')
{
if(y-1 < 0)
{
ok = 0;
continue;
}
c[x][y] = c[x][y - 1];
y--;
c[x][y] = ' ';
}
else if(ch == 'R')
{
if(y+1 > 4)
{
ok = 0;
continue;
}
c[x][y] = c[x][y + 1];
y++;
c[x][y] = ' ';
}
else if(ch == 'A')
{
if(x-1 < 0)
{
ok = 0;
continue;
}
c[x][y] = c[x - 1][y];
x--;
c[x][y] = ' ';
}
else if(ch == 'B')
{
if(x+1 > 4)
{
ok = 0;
continue;
}
c[x][y] = c[x + 1][y];
x++;
c[x][y] = ' ';
}
//cout << "x=" << x << " y=" << y << endl;
}
}
if(flag) cout << endl;
printf("Puzzle #%d:\n",++cnt);
if(ok)
{
for(int i = 0; i < 5; ++i)
{
for(int j = 0; j < 5; ++j)
{
//if(i)
if(j) cout << " ";
cout << c[i][j];
}
cout << endl;
}
}
else
cout << "This puzzle has no final configuration." << endl;
flag++;
getchar();
}
return 0;
}
输入数据让我费了好大劲,从scanf换为%c(自己实在是找不出哪里出了问题一直WA,可能是换行符?我也处理过了啊),最后换为gets过了。