Continue IDA * search, and the valuation function H is still the Manhattan distance. Each conversion will change the Manhattan distance in four locations by 1, therefore, the Manhattan distance and + 3/4 can be used as the H function to indicate at least how many steps are required and a DFS pruning is required.
This question can be up to nine steps, and BFS should not be under pressure.
Unfortunately, it was not optimized to 0 MS.
[Cpp]
# Include <iostream>
# Include <cstdio>
# Include <cstring>
# Include <cmath>
# Define LD long double
# Define LL _ int64
# Define M 200005
Using namespace std;
Int T, a [9];
Int depth;
Char str [10];
Bool flag;
Int rotation [4] [4] = }};
Int get_h (int * B ){
Int ans = 0;
For (int I = 0; I <9; I ++)
Ans + = abs (I/3-(B [I]-1)/3) + abs (I % 3-(B [I]-1) % 3 );
Return (ans + 3)/4;
}
Void change (int * B, int kind ){
If (kind & 1 ){
Kind/= 2;
Int tmp = B [rotation [kind] [3];
For (int I = 3; I> 0; I --)
B [rotation [kind] [I] = B [rotation [kind] [I-1];
B [rotation [kind] [0] = tmp;
}
Else {
Kind/= 2;
Int tmp = B [rotation [kind] [0];
For (int I = 1; I <4; I ++)
B [rotation [kind] [I-1] = B [rotation [kind] [I];
B [rotation [kind] [3] = tmp;
}
}
Void IDAstar (int * B, int tmp_depth, int pre ){
If (flag)
Return;
If (get_h (B)> tmp_depth)
Return;
If (tmp_depth = 0 & get_h (B) = 0 ){
Flag = true;
Return;
}
For (int I = 0; I <8; I ++ ){
If (pre> = 0 & pre/2 = I/2 & (pre % 2) ^ (I % 2 ))
Continue;
Int tmp [9];
For (int j = 0; j <9; j ++)
Tmp [j] = B [j];
Change (tmp, I); www.2cto.com
IDAstar (tmp, tmp_depth-1, I );
}
}
Int main (){
Int cas = 0;
While (scanf ("% s", str )! = EOF & strcmp (str, "0000000000 ")){
T = str [0]-'0 ';
For (int I = 0; I <9; I ++)
A [I] = str [I + 1]-'0 ';
Flag = false;
For (depth = get_h (a); depth <= T; depth ++ ){
IDAstar (a, depth,-1 );
If (flag ){
Printf ("% d. % d \ n", ++ cas, depth );
Break;
}
}
If (! Flag)
Printf ("% d.-1 \ n", ++ cas );
}
Return 0;
}
By ACM_cxlove