FZU - 2283 Tic-Tac-Toe (对抗博弈论)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37129433/article/details/81879252

Tic-Tac-Toe

题 意:给你一个3*3的井字棋,已经有了已经下的棋,问下三步之类,alice能不能赢。
输入样例:

3   //三组测试数据
. . .
. . .
. . .
o //alice 执的棋。他先下
o x o
o . x
x x o
x
o x .
. o .
. . x
o

样例输出:

Cannot win!
Kim win!
Kim win!

思 路:对抗博弈论,对于alice 只要有一种下棋的方案他能赢,那么他就能赢,对于他的对手只要有一种方案能让alice不能赢那么他就不能赢。
收 获:收获了一种新的搜索思路

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
using namespace std;
char mp[3][3];
char ch[2];
bool jud(){
    if(mp[0][0] == mp[0][1] && mp[0][1] == mp[0][2] && mp[0][0]!='.') return true;
    if(mp[1][0] == mp[1][1] && mp[1][1]== mp[1][2] && mp[1][0]!='.') return true;
    if(mp[2][0] == mp[2][1] && mp[2][1]== mp[2][2] && mp[2][0]!='.') return true;

    if(mp[0][0] == mp[1][0] && mp[1][0]== mp[2][0] && mp[0][0]!='.') return true;
    if(mp[0][1] == mp[1][1] && mp[1][1]== mp[2][1] && mp[0][1]!='.') return true;
    if(mp[0][2] == mp[1][2] && mp[1][2]== mp[2][2] && mp[0][2]!='.') return true;

    if(mp[0][0] == mp[1][1] && mp[1][1]== mp[2][2] && mp[0][0]!='.') return true;
    if(mp[0][2] == mp[1][1] && mp[1][1]== mp[2][0] && mp[0][2]!='.') return true;

    return false;

}
void view(){
    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            cout<<mp[i][j];
        }
        cout<<endl;
    }
}
bool dfs(int d){
    if(d>3)return false;
    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            if(mp[i][j] == '.'){
                if(d&1){
                    mp[i][j] = ch[0];
                    if(jud()){
                        mp[i][j] = '.';
                        return true;
                    }
                    bool flag = dfs(d+1);
                    mp[i][j] = '.';
                    if(flag){
                        return true;
                    }
                }else{
                    mp[i][j] = ch[1];
                    if(jud()){
                        mp[i][j] = '.';
                        return false;
                    }
                    bool flag = dfs(d+1);
                    mp[i][j] = '.';
                    if(!flag) return false;
                }
            }
        }
    }
    if(d&1) return false;
    else return true;
}
int main(){
    int t;
    cin>>t;
    while(t--){
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                cin>>mp[i][j];
            }
        }
        cin>>ch[0];
        if(ch[0] == 'o') ch[1] = 'x';
        else ch[1] = 'o';
        bool flag = dfs(1);
        if(flag){
            cout<<"Kim win!"<<endl;
        }else{
            cout<<"Cannot win!"<<endl;
        }
    }
    return 0;
}
/*
3
x x o
o o x
x . o
o
*/

猜你喜欢

转载自blog.csdn.net/qq_37129433/article/details/81879252
今日推荐