【codevs1004】四子连棋

problem

solution

codes

//思路:把空白当棋,交替黑白走。
//实现:BFS, 打表判断是否成立
#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){
    //check diagonal 1
    if(s[0]==s[5] && s[5]==s[10] && s[10]==s[15])return 1;
    //check diagonal 2
    if(s[3]==s[6] && s[6]==s[9] && s[9]==s[12])return 1;
    //check row
    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;
    }
    //check col
    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();
        //check
        if(check(t))return st;
        //find O
        int o1=-1, o2;
        for(int i = 0; i < 16; i++){
            if(t[i]=='O'){
                if(o1==-1)o1 = i;
                else o2 = i;
            }
        }
        //o1go
        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)));
            }
        }
        //o2go
        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<<"\n";
    return 0;
}
posted @ 2018-05-29 21:38  gwj1139177410  阅读(114)  评论(0编辑  收藏  举报
选择