#include <stdio.h>
int main()
{
enum { SIZE = 5 };
int kase = 0, i = 0, j = 0, ei, ej, valid;
char puzzle[SIZE][SIZE]; // 行主序存儲:第一個下標行號,第二個下標列號
char c;
while (1)
{
for (i = 0; i < SIZE; ++i)
{
for (j = 0; j < SIZE; ++j)
{
c = getchar();
if (c == 'Z')
return 0; // 函數中直接跳出多重循環,用return
puzzle[i][j] = c;
if (c == ' ')
{
ei = i;
ej = j;
}
}
getchar(); // 換行符
}
valid = 1; // 首先必須認為指令序列合法
do
{
c = getchar();
if (!valid)
continue; // 已經非法了,剩下的指令序列直接讀光
switch (c)
{
case 'A':
if (ei - 1 >= 0)
{
puzzle[ei][ej] = puzzle[ei-1][ej];
puzzle[--ei][ej] = ' ';
}
else
{
valid = 0;
}
break;
case 'B':
if (ei + 1 < SIZE)
{
puzzle[ei][ej] = puzzle[ei+1][ej];
puzzle[++ei][ej] = ' ';
}
else
{
valid = 0;
}
break;
case 'L':
if (ej - 1 >= 0)
{
puzzle[ei][ej] = puzzle[ei][ej-1];
puzzle[ei][--ej] = ' ';
}
else
{
valid = 0;
}
break;
case 'R':
if (ej + 1 < SIZE)
{
puzzle[ei][ej] = puzzle[ei][ej+1];
puzzle[ei][++ej] = ' ';
}
else
{
valid = 0;
}
break;
}
} while (c != '0');
getchar(); // 0後面的換行符
if (kase)
putchar('\n');
printf("Puzzle #%d:\n", ++kase);
if (valid)
{
for (i = 0; i < SIZE; ++i)
{
for (j = 0; j < SIZE-1; ++j)
printf("%c ", puzzle[i][j]);
printf("%c\n", puzzle[i][SIZE-1]);
}
}
else
{
printf("This puzzle has no final configuration.\n");
}
}
return 0;
}