您的位置:首页 > 其它

POJ - 1568 Find the Winning Move 极小极大搜索+alpha-beta剪枝

2017-10-02 15:44 369 查看
题目:在一个4*4的格子里面,x和o两个人玩游戏,x画'x',o画'o',x先手,给定x和o都已经画了一定步数的局面,问x是不是必胜的,如果是,输出他应该画在哪个位置

思路:极小极大搜索+alpha-beta剪枝

代码:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<algorithm>
#include<ctime>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<list>
#include<numeric>
using namespace std;
#define LL long long
#define ULL unsigned long long
#define INF 0x3f3f3f3f
#define mm(a,b) memset(a,b,sizeof(a))
#define PP puts("*********************");
template<class T> T f_abs(T a){ return a > 0 ? a : -a; }
template<class T> T gcd(T a, T b){ return b ? gcd(b, a%b) : a; }
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
// 0x3f3f3f3f3f3f3f3f
//0x3f3f3f3f

char str[10][10];
int chess;
int check(int r,int c){
int cnt=0;
for(int i=0;i<4;i++)//同一行
if(str[r][i]=='x') cnt++;
else if(str[r][i]=='o') cnt--;
if(cnt==4||cnt==-4) return 1;

cnt=0;
for(int i=0;i<4;i++)//同一列
if(str[i][c]=='x') cnt++;
else if(str[i][c]=='o') cnt--;
if(cnt==4||cnt==-4) return 1;

cnt=0;
for(int i=0;i<4;i++)//正对角线
if(str[i][i]=='x') cnt++;
else if(str[i][i]=='o') cnt--;
if(cnt==4||cnt==-4) return 1;

cnt=0;
for(int i=0;i<4;i++)//反对角线
if(str[i][3-i]=='x') cnt++;
else if(str[i][3-i]=='o') cnt--;
if(cnt==4||cnt==-4) return 1;
return 0;
}
int MaxSearch(int x,int y,int alpha);
int MinSearch(int x,int y,int beta);
int MinSearch(int x,int y,int beta){
int ans=1;
if(check(x,y)) return ans;//x win
if(chess==16) return 0;//x not win
for(int i=0;i<4;i++)
for(int j=0;j<4;j++){
if(str[i][j]!='.')
continue;
str[i][j]='o';
chess++;
int tmp=MaxSearch(i,j,ans);
str[i][j]='.';
chess--;
if(ans>tmp) ans=tmp;
if(ans<=beta) return ans;
}
return ans;
}
int MaxSearch(int x,int y,int alpha){
int ans=0;
if(check(x,y)) return ans;//o win
if(chess==16) return 0;//x not win
for(int i=0;i<4;i++)
for(int j=0;j<4;j++){
if(str[i][j]!='.')
continue;
str[i][j]='x';
chess++;
int tmp=MinSearch(i,j,ans);
str[i][j]='.';
chess--;
if(ans<tmp) ans=tmp;
if(ans>=alpha) return ans;
}
return ans;
}
int solve(int &x,int &y){
for(x=0;x<4;x++)
for(y=0;y<4;y++){
if(str[x][y]!='.')
continue;
str[x][y]='x';
chess++;
if(MinSearch(x,y,0)==1)
return 1;
str[x][y]='.';
chess++;
}
return 0;
}
int main(){

// freopen("D:\\input.txt","r",stdin);
// freopen("D:\\output.txt","w",stdout);
char ch[10];
while(~scanf("%s",ch)){
if(ch[0]=='$')
break;
for(int i=0;i<4;i++)
scanf("%s",str[i]);
chess=0;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
if(str[i][j]!='.')
chess++;
int x,y;
if(solve(x,y)) printf("(%d,%d)\n",x,y);
else printf("#####\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: