
题意:输入5x5的字符串,输入操作,要求输出完成操作后的字符串。
注意:①输入的操作执行可能会越界,如果越界则按题目要求输出不能完成的语句。
②除了最后一次的输出外,其他输出均要在后面空一行。
③操作的最后一个换行符可能会占据str[0],需要用c来getchar()
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int noConfig=,x,y,findEmpty=,count=,cmdcount=;
//noConfig是指令不能执行(越界时),findEmpty是一边输入一边查找空字符的时候用,1为找到
//count是puzzle的计数,cmdcount是命令的计数
char str[][],cmd[];
//str是输入的字符串,cmd是操作指令
int judge(int exi,int exj)//判断越界
{
if(exi<||exi>=||exj<||exj>=)
{
return -;
}
return ;
} int swap(int i,int j,char cmd)//str[exi][exj]交换str[i][j]中的空字符
{
int exi,exj;
// printf(" i=%d j=%d cmd=%c\n",i,j,cmd);
switch (cmd)
{
case 'A':
exi=i-;
exj=j;
break;
case 'B':
exi=i+;
exj=j;
break;
case 'L':
exi=i;
exj=j-;
break;
case 'R':
exi=i;
exj=j+;
break;
}
// printf("exi=%d exj=%d\n",exi,exj);
//判断
if(judge(exi,exj)==-)
{
noConfig=;
return -;
}
//交换
str[y][x]=str[exi][exj];
// printf(" Y,X:str[%d][%d]=%c\n",y,x,str[y][x]);
str[exi][exj]=' ';
// printf(" EXI,EXJ:str[%d][%d]=%c\n",y,x,str[exi][exj]);
y=exi;
x=exj;
// printf("after change:\n");
// for(i=0;i<5;i++)
// {
// for(j=0;j<5;j++)
// {
// printf("%c",str[i][j]);
// }
// printf("\n");
// }
return ;
} int main()
{
char c;
int i,j,k;
while()
{
noConfig=;
cmdcount=;
memset(str,'\0',sizeof(str));
for(i=;i<;i++)
{
gets(str[i]);
if(str[][]=='Z')
{
return ;
}
// for(j=0;j<5;j++)//边输入边查找
// {
// if(str[i][j]==' '||str[i][j]=='\0')
// {
// x=j;
// y=i;
// findEmpty=1;
//// printf("Y=%d X=%d\n",y,x);
// }
// }
}
for(i=;i<;i++)
{
for(j=;j<;j++)
{
if(str[i][j]==' '||str[i][j]=='\0')
{
x=j;
y=i;
// printf("Y=%d X=%d\n",y,x);
}
}
}
count++;
while((c=getchar())!='')
{
cmd[cmdcount++]=c;
}
c=getchar();//用c取最后的换行符,不然str[0]会被换行符占据
for(i=;i<cmdcount;i++)
{
if(swap(y,x,cmd[i])==-)
break;
}
// fflush(stdin);写了这个就TIE
//输出结果
if(count!=)
printf("\n");//注意这里,除最后一个输出外,其他的输完后都空一行
if(noConfig==)//无结果
{
printf("Puzzle #%d:\n",count);
printf("This puzzle has no final configuration.\n");
}
else
{
printf("Puzzle #%d:\n",count);
//输出
for(i=;i<;i++)
{
for(j=;j<;j++)
{
if(j!=)
printf(" ");
printf("%c",str[i][j]);
}
printf("\n");
}
}
}
return ;
}