Exercises --- puzzles

1, Title
There is a 5 * 5 grid, in which exactly one grid is empty and the other grids each have a letter. There are four kinds of instructions: A, B, L, R, which means to move the adjacent letters above, below, left and right of the space into the space. Input the initial grid and instruction sequence (ending with the number 0), and output the grid after the instruction execution. If there is an illegal instruction, "This puzzle has no final configuration."

For example, after performing ARRBBL0 in Figure 3-5, the effect is shown in Figure 3-6.

2, Thinking
The input of the topic is not clear, so I set it as: read the map one line, read the operation one line
We can use the method of no interval input (except for the starting point of the space). Then, we can use the method of substitution to realize this problem. If there is an illegal instruction, we can return it after encountering the direct printf.

3, Code

```#include <stdio.h>
#include<string.h>

//char s[100][100]={"TRGSJ","XDOKI","M VLN","WPABE","UQHCF"};

char s[100][100];     //Map string
char operat[10000];   //Operation string
int main ()
{
int i=0;
int j=0;
int tx,ty;       //Abscissa and ordinate of space
char tempc;

for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
scanf("%c",&s[i][j]);
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(s[i][j]==' ')
{
tx=i;
ty=j;
break;

}
}
}
getchar();          // To clear the carriage return
gets(operat);
i=j=0;
tempc = operat[i];

//The following is just to control which two are replaced according to the operation character and track the coordinates of the space with TX and ty
while(tempc!='0')
{
char tt;
switch(tempc)
{
case 'A' :{tt = s[tx-1][ty];    s[tx-1][ty] = ' ';  s[tx][ty]=tt;   tx=tx-1;break;}
case 'B' :{tt = s[tx+1][ty];    s[tx+1][ty] = ' ';  s[tx][ty]=tt;   tx=tx+1;break;}
case 'R' :{tt = s[tx][ty+1];    s[tx][ty+1] = ' ';  s[tx][ty]=tt;   ty=ty+1;break;}
case 'L' :{tt = s[tx][ty-1];    s[tx][ty-1] = ' ';  s[tx][ty]=tt;   ty=ty-1;break;}
default :{printf("This puzzle has nofinal configuration.\n");return;}
}
i++;
tempc = operat[i];
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
printf("%c ",s[i][j]);
}
printf("\n");
}
return 0;
}
```

Posted on Mon, 20 Apr 2020 10:40:46 -0700 by jamal dakak