搜索 C. Tic-tac-toe

39 篇文章 0 订阅

Problem - C - Codeforces

image-20231126001519574

思路:搜索,判断合法性。从起始态用搜索进行模拟,这样可以避免后面判断合法性这一繁琐的步骤。用一个map进行映射当前态及对应的结果。剪枝:如果当前字符串已经被搜索过,则直接跳过去。

代码实现:

void solve() {
	array<string, 3> st;
	cin>>st[0]>>st[1]>>st[2];
	array<string, 3> ph;
	ph[0] = "...";
	ph[1] = "..."; ph[2] = "...";
	map<array<string,3>, string> mp;
	// 判断是否赢
	auto check = [&](char ch) -> bool {
		// 行
		for(int i = 0; i < 3; ++i) {
			bool ok = true;
			for(int j = 0; j < 3; ++j) {
				ok &= ph[i][j] == ch;
			}
			if(ok) return 1;
		}
		// 列
		for(int i = 0; i < 3; ++i) {
			bool ok = true;
			for(int j = 0; j < 3; ++j) {
				ok &= ph[j][i] == ch;
			}
			if(ok) return 1;
		}
		// 对角线
		if(ph[0][0] == ch && ph[1][1] == ch && ph[2][2] == ch) return 1;
		if(ph[2][0] == ch && ph[1][1] == ch && ph[0][2] == ch) return 1;
		return 0;
	};

	// 先是A X
	// B 0
	// 从起始态进行搜索
	auto dfs = [&](auto&& self, int step) -> void {
		if(check('X')) {
			mp[ph] = "the first player won";
			return ;
		} else if(check('0')) {
			mp[ph] = "the second player won";
			return ;
		} else if(step == 9) {
			mp[ph] = "draw";
			return ;
		}
		mp[ph] = step % 2 == 0 ? "first" : "second";
		for(int i = 0; i < 3; ++i) {
			for(int j = 0; j < 3; ++j) {
				if(ph[i][j] != '.') continue;
				ph[i][j] = step % 2 == 0 ? 'X' : '0';
				if(mp.find(ph) == mp.end())
					self(self, step + 1);
				ph[i][j] = '.';
			}
		}
	};
	dfs(dfs, 0);
	// 如果在合法态中没有找到就是非法的。
	if(mp.find(st) == mp.end()) cout<<"illegal";
	else {
		cout<<mp[st];
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

golemon.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值