Http://poj.org/problem? Id = 2965
The 16 locations have two states, which are represented by a 16-bit binary. Beg is obtained by bitwise OR calculation. In BFs, use a hexadecimal number that contains only 0, 1 to implement the flip operation.
The rest is simply BFs.
Code:
# Include <iostream>
# Include <cstdio>
# Include <cstring>
Using namespace STD;
Int dir [16] = {0x111f, 0x222f, 0x444f, 0x888f,
0x11f1, 0x22f2, 0x44f4, 0x88f8,
0x1f11, 0x2f22, 0x4f44, 0x8f88,
0xf111, 0xf222, 0xf444, 0xf888 };
Bool vis [1 <17];
Int beg;
Struct data {
Int pre, step, value, X, Y;
} Q [1 <17];
Void BFS (){
Int head, end;
Data temp, T;
Head = END = 0;
Temp. value = beg;
Temp. Step = 0;
Q [head] = temp;
End = 1;
Vis [beg] = 1;
While (end> head ){
Temp = Q [head ++];
For (INT I = 0; I <16; I ++ ){
T = temp;
T. Value ^ = dir [I];
If (! Vis [T. value]) {
Vis [T. value] = 1;
T. Step = Q [head-1]. Step + 1;
T. Pre = head-1;
T. X = I/4 + 1;
T. Y = I % 4 + 1;
If (T. value = 0 ){
Printf ("% d \ n", T. Step );
While (T. Step ){
Printf ("% d \ n", T. x, t. y );
T = Q [T. Pre];
}
Return;
}
Q [end ++] = T;
}
}
}
}
Int main (){
Int I, J;
Char;
Beg = 0;
For (I = 0; I <16; I ++ ){
Cin>;
If (A = '+') beg | = 1 <I;
}
Memset (VIS, 0, sizeof (VIS ));
BFS ();
Return 0 ;}