有一个5×5的网格,其中恰好有一个格子是空的,其他格子各有一个字母,一共有四种指令:A,B,L,R,分别表示把空格上、下、左、右的相邻字母移到空格中。输入初始网格和指令序列(分别以数字0结束),输出指令执行完毕后的网格。如果有非法指令,应输出"This puzzle has no final configuration.",例如,图执行ARRBBL0后,效果如图所示:
//不使用函数
#include <stdio.h>
char mat[6][6];
char com[1000];
int spx, spy; //空格列和行
int main()
{
int i, flag = 1;
while(gets(mat[0]))
{
flag = 1;
for(i = 1; i < 5; i++)
{
gets(mat[i]);
}
gets(com);
for(int j = 0; j < 5; j++)
{
for(int k = 0; k < 5; k++)
{
if(mat[j][k] == ' ')
{
spy = j;
spx = k;
}
}
}
i = 0;
while(com[i] != '\0')
{
if(com[i] == 'A')
{
if(spy-1 < 0)
{
printf("This puzzle has no final configuration.\n");
flag = 0;
break;
}
else
{
mat[spy][spx] = mat[spy-1][spx];
mat[--spy][spx] = ' ';
}
}
if(com[i] == 'B')
{
if(spy+1 > 4)
{
printf("This puzzle has no final configuration.\n");
flag = 0;
break;
}
else
{
mat[spy][spx] = mat[spy+1][spx];
mat[++spy][spx] = ' ';
}
}
if(com[i] == 'L')
{
if(spx-1 < 0)
{
printf("This puzzle has no final configuration.\n");
flag = 0;
break;
}
else
{
mat[spy][spx] = mat[spy][spx-1];
mat[spy][--spx] = ' ';
}
}
if(com[i] == 'R')
{
if(spx+1 > 4)
{
printf("This puzzle has no final configuration.\n");
flag = 0;
break;
}
else
{
mat[spy][spx] = mat[spy][spx+1];
mat[spy][++spx] = ' ';
}
}
i++;
}
if(flag)
{
for(int j = 0; j < 5; j++)
{
for(int k = 0; k < 5; k++)
{
printf("%c", mat[j][k]);
}
printf("\n");
}
}
}
return 0;
}
或
//使用函数
#include <stdio.h>
char mat[6][6];
char com[1000];
int spx, spy; //空格列和行
int main()
{
int i, flag = 1;
while(gets(mat[0]))
{
flag = 1;
for(i = 1; i < 5; i++)
{
gets(mat[i]);
}
gets(com);
for(int j = 0; j < 5; j++)
{
for(int k = 0; k < 5; k++)
{
if(mat[j][k] == ' ')
{
spy = j;
spx = k;
}
}
}
i = 0;
while(com[i] != '\0')
{
if(com[i] == 'A')
{
if(spy-1 < 0)
{
printf("This puzzle has no final configuration.\n");
flag = 0;
break;
}
else
{
mat[spy][spx] = mat[spy-1][spx];
mat[--spy][spx] = ' ';
}
}
if(com[i] == 'B')
{
if(spy+1 > 4)
{
printf("This puzzle has no final configuration.\n");
flag = 0;
break;
}
else
{
mat[spy][spx] = mat[spy+1][spx];
mat[++spy][spx] = ' ';
}
}
if(com[i] == 'L')
{
if(spx-1 < 0)
{
printf("This puzzle has no final configuration.\n");
flag = 0;
break;
}
else
{
mat[spy][spx] = mat[spy][spx-1];
mat[spy][--spx] = ' ';
}
}
if(com[i] == 'R')
{
if(spx+1 > 4)
{
printf("This puzzle has no final configuration.\n");
flag = 0;
break;
}
else
{
mat[spy][spx] = mat[spy][spx+1];
mat[spy][++spx] = ' ';
}
}
i++;
}
if(flag)
{
for(int j = 0; j < 5; j++)
{
for(int k = 0; k < 5; k++)
{
printf("%c", mat[j][k]);
}
printf("\n");
}
}
}
return 0;
}