标签:
#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;
}
标签:
原文地址:http://www.cnblogs.com/danny1221/p/4591975.html