要点:
1.scanf(” %c”,&c),(注意前面的空格)可以跳过换行符等
第一次照网上的代码打的如下,虽然简化了代码,要注意行和列
#include<stdio.h>
#include<string.h>
char map[5][5];
const int y[] = { 0,0,1,-1 };
const int x[] = { -1,1,0,0 };
int tra[110]; //移动行所在的数组
bool legal(int pos)
{
return 0 <= pos&&pos < 5; //判断是否越界
}
void pmap()
{
for (int row = 0; row < 5; row++)
{
printf("%c", map[row][0]);
for (int col = 1; col < 5; col++)
printf(" %c", map[row][col]); //分开输出,确保每个间隔一个空格
printf("\n");
}
}
int main()
{
tra['A'] = 0;
tra['B'] = 1;
tra['R'] = 2;
tra['L'] = 3;
bool first = true; //使第一个矩阵不空行,从第二个矩阵开始空行
int n = 1;
int bx, by;
while (gets(map[0])) //先输入第一行判断是否为Z
{ //gets不符合C11标准
if (map[0][0] == 'Z')
break;
for (int row = 1; row < 5; row++)
gets(map[row]);
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
if (map[i][j] == ' ')
{
bx = i; //x对应的是列,y对应行
by = j;
}
bool ok = true;
char c;
while (scanf(" %c", &c), c != '0') //%c前空一格可跳过换行符,使移动行可以多行输入
{
if (!ok)
continue;
int nx = bx + x[tra[c]], ny = by + y[tra[c]];
if (!legal(nx)||!legal(ny))
{
ok = false;
continue;
}
map[bx][by] = map[nx][ny];
map[nx][ny] = ' ';
bx = nx; by = ny;
}
getchar(); //最后用getchar吃掉一个换行符
if (first)
first = false;
else
printf("\n");
printf("Puzzle #%d:\n", n++);
if (ok)
pmap();
else
printf("This puzzle has no final configuration.\n");
}
return 0;
}
第二次尝试用简单的办法,自己敲得的代码如下,虽然麻烦但好在行列变换易于理解
#include<stdio.h>
char map[5][5];
int bx,by,nx,ny;
bool legal(int pos)
{
return 0<=pos&&pos<5;
}
void pmap()
{
for(int row=0;row<5;row++)
{
printf("%c",map[row][0]);
for(int col=1;col<5;col++)
printf(" %c",map[row][col]);
printf("\n");
}
}
void swap(int bx,int by,int nx,int ny)
{
map[bx][by]=map[nx][ny];
map[nx][ny]=' ';
}//bx,by不能在函数中赋值,要用指针
int main()
{
bool first=true;
int n=1;
while(gets(map[0]))
{
if(map[0][0]=='Z')
break;
for(int row=1;row<5;row++)
gets(map[row]);
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
if(map[i][j]==' ')
{
bx=i;
by=j;
}
bool ok=true;
char c;
while(scanf(" %c",&c),c!='0')
{
if(!ok)
continue;
if(c=='A')
{
nx=bx-1;ny=by;
if(!legal(nx)||!legal(ny))
{
ok=false;
continue;
}
swap(bx,by,nx,ny);
bx=nx;by=ny;
}
if(c=='B')
{
nx=bx+1;ny=by;
if(!legal(nx)||!legal(ny))
{
ok=false;
continue;
}
swap(bx,by,nx,ny);
bx=nx;by=ny;
}
if(c=='L')
{
nx=bx;ny=by-1;
if(!legal(nx)||!legal(ny))
{
ok=false;
continue;
}
swap(bx,by,nx,ny);
bx=nx;by=ny;
}
if(c=='R')
{
nx=bx;ny=by+1;
if(!legal(nx)||!legal(ny))
{
ok=false;
continue;
}
swap(bx,by,nx,ny);
bx=nx;by=ny;
}
}
getchar();
if(first)
first=false;
else
printf("\n");
printf("Puzzle #%d:\n", n++);
if (ok)
pmap();
else
printf("This puzzle has no final configuration.\n");
}
return 0;
}