POJ 1753
BFS可以延伸的应用变化繁多,这道题配合状态压缩共同解决,不过时空复杂度还可以进一步优化。
#include <iostream>
#include <algorithm>
#include <queue>
#include <string>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <stack>
#include <map>
#include <set>
using namespace std;
const int maxl= 16;
const int maxs= (1<<maxl)+5;
const int maxn= 6;
const int WHITE= 0;
const int BLACK= 1;
const int END0= 0;
const int ENDI= 0xffff;
int bod[maxl+5];
int vis[maxs], dis[maxs];
int flip[maxs];
int Encode(int *code, int m)
{
int st= 0;
for (int i= m-1; i>= 0; --i){
st<<= 1;
st|= code[i];
}
return st;
}
inline void FlipInit(const int m)
{
int x;
for (int i= 0; i< m; ++i){
x= 1<<i;
if (i-4>= 0 && i-4< m){
x|= 1<<(i-4);
}
if (i+4>= 0 && i+4< m){
x|= 1<<(i+4);
}
if (i & 3){
x|= 1<<(i-1);
}
if ((i+1) & 3){
x|= 1<<(i+1);
}
flip[i]= x;
}
}
int BFS()
{
int st= Encode(bod, maxl), n_st;
if (END0== st || ENDI== st){
return 0;
}
queue<int> Q;
memset(vis, 0, sizeof(vis));
FlipInit(maxl);
int ans= 0;
vis[st]= 1;
dis[st]= 0;
Q.push(st);
while (!Q.empty()){
st= Q.front();
Q.pop();
ans= dis[st]+1;
for (int i= 0; i< maxl; ++i){
n_st= st ^ flip[i];
if (END0== n_st || ENDI== n_st){
return ans;
}
if (!vis[n_st]){
vis[n_st]= 1;
dis[n_st]= ans;
Q.push(n_st);
}
}
}
return -1;
}
int main()
{
char in_s[maxn];
int k= 0, ans;
for (int i= 1; i<= 4; ++i){
scanf("%s", in_s+1);
for (int j= 1; j<= 4; ++j){
bod[k++]= 'b'== in_s[j] ? BLACK : WHITE;
}
}
ans= BFS();
if (-1== ans){
printf("Impossible");
}
else{
printf("%d", ans);
}
return 0;
}