解体思路:二维数组储存原型,记录空格位置,按顺序移动,移动越界即为This puzzle has no final configuration.
注意:1、这个题输出格式卡的我老是WA,注意具体那个空行的位置
TRGSJ
XDOKI
M VLN
WPABE
UQHCF
ARRBBL0
Puzzle #1:
T R G S J
X O K L I
M D V B N
W P A E
U Q H C F
ABCDE
FGHIJ
KLMNO
PQRS
TUVWX
AAA
LLLL0
Puzzle #2:
A B C D
F G H I E
K L M N J
P Q R S O
T U V W X
ABCDE
FGHIJ
KLMNO
PQRS
TUVWX
AAAAABBRRRLL0
Puzzle #3:
This puzzle has no final configuration.
Z
Process returned 0 (0x0) execution time : 16.359 s
Press any key to continue.
2、这个题读取原型时,也应注意不要用scanf,因为有空格!
AC代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j,x,y,t=1,flag;
char a[10][10];
while(1)
{
flag=0;
for (i=0;i<5;i++)
{
for (j=0;j<5;j++)
{
a[i][j]=getchar();
if (a[0][0]=='Z') return 0;
if (a[i][j]==' ') {x=i; y=j;}
}
getchar();
}
char commd;
while((commd=getchar())&&commd!='0')
{
if (flag) continue;
if (commd=='A')
{
if (x==0) {flag=1;continue;}
a[x][y]=a[x-1][y];
a[x-1][y]=' ';
x--;
}
else if (commd=='B')
{
if (x==4) {flag=1;continue;}
a[x][y]=a[x+1][y];
a[x+1][y]=' ';
x++;
}
else if (commd=='L')
{
if (y==0) {flag=1;continue;}
a[x][y]=a[x][y-1];
a[x][y-1]=' ';
y--;
}
else if (commd=='R')
{
if (y==4) {flag=1;continue;}
a[x][y]=a[x][y+1];
a[x][y+1]=' ';
y++;
}
}
if (t-1) putchar('\n');
printf("Puzzle #%d:\n",t++);
if (!flag)
{
for (i=0;i<5;i++)
{
for (j=0;j<5;j++)
{
if (!j) printf("%c",a[i][j]);
else printf(" %c",a[i][j]);
}
putchar('\n');
}
}
else
printf("This puzzle has no final configuration.\n");
getchar();
}
return 0;
}