1.提醒一下自己初始化很重要。
2.因为自己在solve()中使用for(int i = 0; i < strlen(command); i++)
没注意到strlen(command)返回的是最长的命令输入的字符个数而不是当前字符个数导致无法AC
eg:command 接收到 “LLLRRRAAA”的输入 command为 “LLLRRRAAA”(末尾没有\0)
然后 command 接收到 “BBB”的输入后 command为 “BBBRRRAAA”,strlen(command)返回的是一个大于等于9的数(strlen()遇到’\0’才返回),而不是3;
3.自己为solve()添加了一个整型变量 n用于统计字符个数解决了
下面是AC代码
#include <stdio.h>
#include <string.h>
char command[100000];
char a[5][5];
int pos[2]; //X:pos[0] Y:pos[1]
bool f;
void swap(char *a,char *b)
{
char t = *a;
*a = *b;
*b = t;
}
void solve(int n) //原来的错误代码 solve()
{
for(int i = 0; i < n; i++) //原来的错误代码 for(int i = 0; i < strlen(commmand);i++)
{
char c = command[i];
if(c == 'A')
{
if(pos[1] - 1 >= 0)
{
swap(&a[pos[1]][pos[0]],&a[pos[1] - 1][pos[0]]);
pos[1] -= 1;
}
else
f = false;
}
else if (c == 'B')
{
if(pos[1] + 1 <= 4)
{
swap(&a[pos[1]][pos[0]],&a[pos[1] + 1][pos[0]]);
pos[1] += 1;
}
else
f = false;
}
else if (c == 'L')
{
if(pos[0] - 1 >= 0)
{
swap(&a[pos[1]][pos[0]],&a[pos[1]][pos[0] - 1]);
pos[0] -= 1;
}
else
f = false;
}
else if (c == 'R')
{
if(pos[0] + 1 <= 4)
{
swap(&a[pos[1]][pos[0]],&a[pos[1]][pos[0] + 1]);
pos[0] += 1;
}
else
f = false;
}
}
}
int main()
{
int kase = 0;
while(1) {
f = true;
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
a[i][j] = getchar();
if(a[0][0] == 'Z') return 0;
if(a[i][j] == ' ') { pos[0] = j; pos[1] = i;}
}
getchar();
}
int n = 0;
while(scanf(" %c",&command[n]) == 1)
{
if(command[n] == '0') break;
else n++;
}
getchar(); //舍弃命令输入中的回车符
solve(n); //原来的错误代码 solve();
if(kase++) printf("\n");
printf("Puzzle #%d:\n",kase);
if(f)
{
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
if(j) printf(" ");
printf("%c",a[i][j]);
}
printf("\n");
}
}
else
printf("This puzzle has no final configuration.\n");
}
return 0;
}