poj [1753]

棋盘的上的每一个状态对应一个二进制串,以初始状态为跟节点建树,然后广度优先遍历这颗树,层数为所求的值。

#include<iostream>   

#include<queue>   

#define ALL_WHITE 0   

#define ALL_BLACK 65535   

using namespace std;   

int states[65536];   

int state,temp;   

int flip(int state_current, int pos) {   

    state_current ^= (1 << pos);   

    if (pos - 4 >= 0) {   

        state_current ^= (1 << (pos - 4));   

    }   

    if (pos + 4 < 16) {   

        state_current ^= (1 << (pos + 4));   

    }   

    if (pos % 4 != 0) {   

        state_current ^= (1 << (pos - 1));   

    }   

    if (pos % 4 != 3) {   

        state_current ^= (1 << (pos + 1));   

    }   

    return state_current;   

}   

void bfs() {   

    int i;   

    memset(states,-1,sizeof(states));   

    queue<int> q;   

    states[state] = 0;   

    q.push(state);   

    if (state == ALL_BLACK || state == ALL_WHITE){   

        cout<<"0"<<endl;   

        return ;   

    }   

    while(!q.empty()){   

        temp=q.front();   

        q.pop();   

        for(i=0;i<16;i++) {   

            int next_state = flip(temp, i);   

            if (next_state == ALL_BLACK || next_state == ALL_WHITE){   

                cout<<states[temp]+1<<endl;   

                return ;   

            }   

            if (states[next_state] == -1){   

                states[next_state] = states[temp] + 1;   

                q.push(next_state);   

            }   

        }   

    }   

    cout<<"Impossible"<<endl;   

}   

int main(){   

    char c;   

    int i;   

    state = 0;   

    for(i=0; i<16; i++){   

        cin>>c;   

        if(c=='b'){   

            state += 1<<i;   

        }   

        if (c == 'w'){   

            state += 0<<i;   

        }   

    }   

    bfs();   

    return 0;   

}



你可能感兴趣的:(poj)