POJ1753 Flip Game

题目链接

分析:

枚举所有的操作。将每个4*4的状态用一个 int 表示, 从0 ~ 15编号。 用BFS 枚举每一种操作。

#include <cstdio>
#include <cmath>
#include <iostream>
#include <queue>
#include <cstring>

using namespace std;
const int maxn = (1<<16);
const int ntype = (1<<16);

queue<int> Q;
bool vis[maxn];
int step[maxn];

void init() {
    memset(vis, false, sizeof(vis));

    char s[5];
    int state = 0;
    for(int i=0; i<4; i++) {
        cin >>s;
        for(int j=0; j<4; j++) {
            state <<= 1;
            if(s[j] == 'w') state |= 1;
        }
    }
    Q.push(state);
    vis[state] = true;
    step[state] = 0;
}

int flip(int state, int i) {
    int nflip = 0;
    nflip |= (1<<i);
    if((i+1) % 4 != 0) nflip |= (1<<(i+1));
    if(i % 4 != 0) nflip |= (1<<(i-1));
    if((i-4) >=0) nflip |= (1<<(i-4));
    if((i+4) < 16) nflip |= (1<<(i+4));
    state ^= nflip;
    return state;
}

bool BFS() {
    while(!Q.empty()) {
        int state = Q.front(); Q.pop();
        if(state == 0 || state == (ntype-1)) {
            cout << step[state];
            return true;
        }
        for(int i=0; i<16; i++) {
            int t = flip(state, i);
            if(!vis[t]) {
                Q.push(t);
                vis[t] = true;
                step[t] = step[state]+1;
            }
        }
    }
    return false;
}

int main(){
    init();

    if(!BFS()) cout << "Impossible\n";

    return 0;
}

 

posted on 2013-06-11 10:51  Still_Raining  阅读(422)  评论(0编辑  收藏  举报