当前位置: 代码迷 >> 综合 >> [CSP]201803-4 棋局评估 min-max搜索
  详细解决方案

[CSP]201803-4 棋局评估 min-max搜索

热度:53   发布时间:2023-12-16 22:18:22.0

题目链接http://118.190.20.162/submitlist.page?gpid=T70

井字棋,现在放了某些棋子。连成线的时候得分为(空格子数+1)(B赢*-1)问当前棋局中,如果Alice和Bob都按最优策略下棋,最终得分。

典型的min-max对抗搜索,A选取分数最高的一种走法,B选取分数最低的一种走法。

注意的是dfs返回值的初始化问题,min搜索初始值不一定小于0, max初始值不一定大于0(因为这个愚蠢的错了好几回)。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int graph[5][5];int judge()//是否结束,返回赢家
{for(int i = 0; i < 3; i++)if(graph[0][i] != 0 && graph[0][i] == graph[1][i] && graph[2][i] == graph[0][i])return graph[0][i];for(int i = 0; i < 3; i++)if(graph[i][0] != 0 && graph[i][0] == graph[i][1] && graph[i][2] == graph[i][0])return graph[i][0];if(graph[0][0] != 0 && graph[0][0] == graph[1][1] && graph[0][0] == graph[2][2])return graph[0][0];if(graph[2][0] != 0 && graph[2][0] == graph[1][1] && graph[2][0] == graph[0][2])return graph[2][0];return 0;
}int getdonow()//当前空格子数
{int cnt = 0;for(int i = 0; i < 3; i++){for(int j = 0; j < 3; j++){if(graph[i][j] == 0)cnt++;}}return cnt;
}int dfs(int donow)
{int person = donow % 2;//当前操作者if(person == 0)person = 2;if(judge() != 0)return person == 2? donow+1 : -donow-1;//此时已结束,有赢家if(donow == 0)return 0;//此时已结束,平局int retmax = -100, retmin = 100;//完全可以合成一个写for(int i = 0; i < 3; i++){for(int j = 0; j < 3; j++){if(graph[i][j] == 0){graph[i][j] = person;//准备下一步递归if(person == 1)retmax = max(retmax, dfs(donow-1));//maxelse retmin = min(retmin, dfs(donow-1));//mingraph[i][j] = 0;//回溯}}}if(person == 1)return retmax;else return retmin;
}int main()
{int T;int flag;int donow;scanf("%d", &T);while(T--){memset(graph, 0, sizeof(graph));for(int i = 0; i < 3; i++){scanf("%d%d%d", &graph[i][0], &graph[i][1], &graph[i][2]);}donow = getdonow();int ans = dfs(donow);if(ans > 0 && ans % 2 == 0)ans++;//如果题目严谨,没有什么用else if(ans < 0 && ans % 2 == 1)ans --;printf("%d\n", ans);}return 0;
}