链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=163
code
#include<stdio.h>
#include<ctype.h>
char puzzle[5][5];
bool move(char chs[5][5], int x,int y, int deX,int deY)
{
bool flag = true;
if( x + deX >= 0 && x + deX < 5 && y + deY >= 0 && y + deY < 5 )
{
char temp = chs[x][y];
chs[x][y] = chs[x + deX][y + deY];
chs[x + deX][y + deY] = temp;
}
else flag = false;
return flag;
}
int main()
{
char ch;
int index = 1;
while(gets(puzzle[0]))
{
int x,y;
if(puzzle[0][0]=='Z')break;
for(int col=1;col<5;col++)
gets(puzzle[col]);
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
if(puzzle[i][j]==' '){
x=i;y=j;
break;
}
scanf("%c",&ch);
bool flag = true;
while(!isdigit(ch))
{
if(flag)
{
switch(ch)
{
case 'A':
flag = move(puzzle,x,y,-1,0);
if(flag) x -= 1;
break;
case 'B':
flag = move(puzzle,x,y,1,0);
if(flag) x += 1;
break;
case 'L':
flag = move(puzzle,x,y,0,-1);
if(flag) y -= 1;
break;
case 'R':
flag = move(puzzle,x,y,0,1);
if(flag) y += 1;
break;
}
}
scanf("%c",&ch);
}
if(index != 1)printf("\n");
printf("Puzzle #%d:\n", index);
if(flag)
{
for(int i = 0 ; i < 5 ; i ++ )
{
printf("%c %c %c %c %c",puzzle[i][0],puzzle[i][1],puzzle[i][2],puzzle[i][3],puzzle[i][4]);
printf("\n");
}
}
else printf("This puzzle has no final configuration.\n");
index ++;
scanf("%c",&ch);
}
return 0;
}
注意事项:首先一开始我是用getchar跟scanf来进行每行读取字符,结果老是没读对,暂时还没想出原因,最后一行只读一个字母,后来参考代码改用gets读取一行,然后再判断空格在哪个位置,第二个注意地方是输出,每行输出我一开始多了一个空格,报了WA结果,然后干脆写死每行输出从0到4就通过了