Pawn Transposition
There are n pieces a,n a piece B, in a row on the board. There is an empty space between them, with the "." Say, for example:
Aaa. Bbb
Now you need all the A and B pieces to swap positions. The rules for moving pieces are:
1. A piece can only move to the right, B pieces can only move to the left.
2. Each piece can be moved to an adjacent vacancy.
3. Each piece can skip a different piece and fall into the empty space (a skip B or b skip a).
Aaa. BBB can go: Move a ==> AA. ABBB move B ==> Aaab. Bb
Skip the example: AA. ABBB ==> Aaba. Bb
The following procedure completes the AB transposition function, please carefully read the analysis source code, fills in the underlined part missing content.
#include <stdio.h> #include <string.h> void Move (char* data, int from, int to) {Data[to] = Data[from];
Data[from] = '. ';
int valid (char* data, int k) {if (k<0 | | k>=strlen (DATA)) return 0;
return 1;
} void F (char* data) {int i;
int tag; int dd = 0;
Move direction while (1) {tag = 0;
for (i=0; I<strlen (data); i++) {if (data[i]== '. ') continue;
if (data[i]== ' A ') dd = 1;
if (data[i]== ' B ') dd =-1; if (valid (data, I+DD) && valid (DATA,I+DD+DD) && Data[i+dd]!=data[i] && data[i+dd+dd]== '.')
{//If can jump ... move (data, I, I+DD+DD);
printf ("%s\n", data);
tag = 1;
Break
} if (tag) continue;
for (i=0; I<strlen (data); i++) {if (data[i]== '. ') continue;
if (data[i]== ' A ') dd = 1; if (data[i]== ' B ') dd =-1;
if (valid (data, I+DD) && data[i+dd]== '. ') {//If can move ... if (______________________) continue;
Fill in the blank position move (data, I, I+DD);
printf ("%s\n", data);
tag = 1;
Break
} if (tag==0) break; int main () {char data[] = "AAA."
BBB ";
f (data);
return 0; }
Note: Only the missing code in the underlined section is submitted, do not copy existing code or fill in any superfluous content.
Ideas:
The process of manually simulating this jump will find a rule that, when translated directly, must be "." There are a,b two different letters on both sides of the
So we're going to filter out the same things.
Code:
if (valid (data, I+DD+DD) && valid (DATA,I-DD) &&DATA[I+DD+DD]==DATA[I-DD])
continue;
The complete output process:
Aa. ABBB
Aaba. BB
Aabab. B
AAB. BAB
A.babab
. Ababab
BA. ABAB
BABA. AB
Bababa.
Babab. A
BAB. BAA
B.babaa
BB. Abaa
Bbba. AA
BBB. Aaa