IDDFS+哈希判重
代码怎么这么长
#include<iostream>
#include<cstring>
using namespace std;
int G[4][4],ax,ay,bx,by;
int have[4100000]={0},k;
bool hash[4100000]={0},ok=0;
const int mx[4]={1,-1,0,0};
const int my[4]={0,0,1,-1};
bool equ(int a,int b,int c,int d);
inline bool check(void);
inline bool gethash(int depth);
void init(void);
void IDA(void);
int search(int depth,int color);
bool equ(int a,int b,int c,int d){
if(a!=b||b!=c||c!=d)return 0;
return 1;
}
inline bool check(void){
for(int i=0;i<4;i++){
if(equ(G[i][0],G[i][1],G[i][2],G[i][3]))return 1;
if(equ(G[0][i],G[1][i],G[2][i],G[3][i]))return 1;
}
if(equ(G[0][0],G[1][1],G[2][2],G[3][3]))return 1;
if(equ(G[0][3],G[1][2],G[2][1],G[3][0]))return 1;
return 0;
}
inline bool gethash(int depth){
int va=0;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
va=va*3+G[i][j];
va%=4070017;
if(hash[va]&&have[va]<=depth)return 0;//!!!!!!??????????
have[va]=depth;
return 1;
}
void IDA(void){
for(k=1;k<=10;k++){
search(1,1);
if(ok){
cout<<k;
break;
}
else search(1,2);
if(ok){
cout<<k;
break;
}
}
if(!ok)cout<<"wocao";
}
int search(int depth,int color){
if(depth==k+1)return 0;
for(int i=0;i<4;i++){
int tx=ax+mx[i],ty=ay+my[i];
if(tx<0||tx>3||ty<0||ty>3)continue;
if(G[tx][ty]!=color)continue;
swap(G[tx][ty],G[ax][ay]);
ax=tx;ay=ty;
if(gethash(depth)){
if(check()){
ok=1;
return 1;
}
search(depth+1,3-color);
}
ax-=mx[i];ay-=my[i];
swap(G[tx][ty],G[ax][ay]);
}
for(int i=0;i<4;i++){
int tx=bx+mx[i],ty=by+my[i];
if(tx<0||tx>3||ty<0||ty>3)continue;
if(G[tx][ty]!=color)continue;
swap(G[tx][ty],G[bx][by]);
bx=tx;by=ty;
if(gethash(depth)){
if(check()){
ok=1;
return 1;
}
search(depth+1,3-color);
}
bx-=mx[i];by-=my[i];
swap(G[tx][ty],G[bx][by]);
}
}
void init(void){
memset(hash,0,sizeof(hash));
bool mark=0;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++){
char a;cin>>a;
if(a=='B')G[i][j]=1;
else if(a=='W')G[i][j]=2;
else{
G[i][j]=0;
if(!mark){
ax=i;ay=j;mark=1;
}
else{
bx=i;by=j;
}
}
}
}
int main(){
init();
IDA();
return 0;
}