題目鏈接:http://118.190.20.162/view.page?gpid=T70
思路:博弈論的知識點
用DFS搜索模擬整個下棋的形式,對每一個可以下棋的位置進行下棋,對每一步進行判斷,然後遞歸回溯,的得分最大化,的得分最小化。
AC代碼:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int mp[10][10];
int left(){//計算還剩下多少空沒有填
int cnt=0;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(mp[i][j]==0){
cnt++;
}
}
}
return cnt;
}
bool row(int row,int flag){//判斷行是否處於贏的狀態
if(mp[row][0]==flag&&mp[row][1]==flag&&mp[row][2]==flag){
return true;
}
return false;
}
bool col(int col,int flag){//判斷列是否處於贏的狀態
if(mp[0][col]==flag&&mp[1][col]==flag&&mp[2][col]==flag){
return true;
}
return false;
}
bool check_win(int flag){//檢查當前人是否贏了
if(row(0,flag)||row(1,flag)||row(2,flag)){
return true;
}
if(col(0,flag)||col(1,flag)||col(2,flag)){
return true;
}
if(mp[0][0]==flag&&mp[1][1]==flag&&mp[2][2]==flag){
return true;
}
if(mp[0][2]==flag&&mp[1][1]==flag&&mp[2][0]==flag){
return true;
}
return false;
}
int cal(int flag){//計算贏的人的得分
if(!check_win(flag)){
return 0;
}
return flag==1?left()+1:-(left()+1);
}
int dfs(int person){//person==0代表Alice,person==1代表Bob
if(left()==0){//平局的情況
return 0;
}
int minn=100,maxx=-100;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(mp[i][j]==0){//這個位置可以放棋子
mp[i][j]=person+1;
int tmp=cal(person+1);
if(tmp){//當前這個人已經贏了
mp[i][j]=0;//當前位置置爲0,遞歸回溯
return tmp>0?max(maxx,tmp):min(minn,tmp);//tmp>0表示Alice贏了,需要最大化答案,反之則是Bob贏了,需要最小化答案
}
if(person==0){
maxx=max(maxx,dfs(1));//Alice需要最大化它的值
}
else{
minn=min(minn,dfs(0));//Bob則需要最小化他的值
}
mp[i][j]=0;//重新置爲0,遞歸回溯
}
}
}
return person==0?maxx:minn;
}
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];
}
}
int t1=cal(1),t2=cal(2);
if(t1!=0){//1代表的是Alice,先判斷初始局勢是否已經定輸贏了
cout<<t1<<endl;
continue;
}
if(t2!=0){//2代表的是Bob
cout<<t2<<endl;
continue;
}
cout<<dfs(0)<<endl;
}
return 0;
}
/*
3
1 2 1
2 1 2
0 0 0
2 1 1
0 2 1
0 0 2
0 0 0
0 0 0
0 0 0
*/
參考:https://blog.csdn.net/xbb224007/article/details/79935167