problem
solution
codes
#include<iostream>
#include<algorithm>
#include<string>
#include<queue>
using namespace std;
string s;
struct node{
string ma; int step; char next;
node(string x, int y, char ch):ma(x),step(y),next(ch){}
};
queue<node>q;
int dz[] = {4,-4,1,-1};
char change(char ch){
if(ch == 'B')return 'W';
if(ch == 'W')return 'B';
}
int check(string s){
if(s[0]==s[5] && s[5]==s[10] && s[10]==s[15])return 1;
if(s[3]==s[6] && s[6]==s[9] && s[9]==s[12])return 1;
for(int i = 0; i < 4; i++){
int ok = 1, t = 4*i;
for(int j = 0; j < 4; j++)
if(s[t] != s[t+j])ok = 0;
if(ok)return 1;
}
for(int i = 0; i < 4; i++){
int ok = 1, t = i;
for(int j = 0; j < 4; j++)
if(s[t] != s[t+j*4])ok = 0;
if(ok)return 1;
}
return 0;
}
int bfs(){
while(q.size()){
string t = q.front().ma;
int st = q.front().step;
char ch = q.front().next;
q.pop();
if(check(t))return st;
int o1=-1, o2;
for(int i = 0; i < 16; i++){
if(t[i]=='O'){
if(o1==-1)o1 = i;
else o2 = i;
}
}
for(int i = 0; i < 4; i++){
if(dz[i]==1 && o1%4==3)continue;
if(dz[i]==-1 && o1%4==0)continue;
int nz = o1+dz[i];
if(nz>=0 && nz<16 && t[nz]==ch){
string nt = t;
swap(nt[o1],nt[nz]);
q.push(node(nt,st+1,change(ch)));
}
}
for(int i = 0; i < 4; i++){
if(dz[i]==1 && o2%4==3)continue;
if(dz[i]==-1 && o2%4==0)continue;
int nz = o2+dz[i];
if(nz>=0 && nz<16 && t[nz]==ch){
string nt = t;
swap(nt[o2],nt[nz]);
q.push(node(nt,st+1,change(ch)));
}
}
}
}
int main(){
ios::sync_with_stdio(false);
for(int i = 0; i < 4; i++){
string t; cin>>t; s += t;
}
if(check(s)){ cout<<"0"; return 0;}
int ans = 0xffffff;
q.push(node(s,0,'W'));
ans = min(ans, bfs());
while(q.size())q.pop();
q.push(node(s,0,'B'));
ans = min(ans, bfs());
cout<<ans<<"
";
return 0;
}