这是一个通过输入A、B、L、R四个字母,改变空格在二维数组中的位置的程序
#include<stdio.h>
#include<string.h>
void swap(char * a,char * b)
{
char temp;
temp=*a;
*a=*b;
*b=temp;
}
int main()
{
char s[5][5]={
{'A','B','C','D','E'},
{'F',' ','G','H','I'},
{'J','K','L','M','N'},
{'O','P','Q','R','S'},
{'T','U','V','W','X'}
};//空格在1,1
char c;
int sy=1,sx=1;
int flag=1;
while((c=getchar())!='0')
{
if(strchr("ABLR",c)==NULL)
{
printf("This puzzle has no final configuration.\n");
flag=0;
break;
}
switch(c)
{
case 'A':swap(&s[sy][sx],&s[--sy][sx]); break;
case 'B':swap(&s[sy][sx],&s[++sy][sx]); break;
case 'L':swap(&s[sy][sx],&s[sy][--sx]); break;
case 'R':swap(&s[sy][sx],&s[sy][++sx]);
}
}
if(flag)
for(int i=0;i<=4;i++)
{
for(int j=0;j<=4;j++)
printf("%c ",s[i][j]);
printf("\n");
}
}
#include<stdio.h>
#include<string.h>
void swap(char * a,char * b)
{
char temp;
temp=*a;
*a=*b;
*b=temp;
}
int main()
{
char s[5][5]={
{'A','B','C','D','E'},
{'F',' ','G','H','I'},
{'J','K','L','M','N'},
{'O','P','Q','R','S'},
{'T','U','V','W','X'}
};//空格在1,1
char c;
int sy=1,sx=1;
int flag=1;
while((c=getchar())!='0')
{
if(strchr("ABLR",c)==NULL)
{
printf("This puzzle has no final configuration.\n");
flag=0;
break;
}
switch(c)
{
case 'A':swap(&s[sy][sx],&s[--sy][sx]); break;
case 'B':swap(&s[sy][sx],&s[++sy][sx]); break;
case 'L':swap(&s[sy][sx],&s[sy][--sx]); break;
case 'R':swap(&s[sy][sx],&s[sy][++sx]);
}
}
if(flag)
for(int i=0;i<=4;i++)
{
for(int j=0;j<=4;j++)
printf("%c ",s[i][j]);
printf("\n");
}
}