Zobrist Hash算法的基础:按位异或运算的性质

本文介绍了ZobristHash算法的基本原理及其在棋类程序中的应用。通过C++代码示例展示了如何使用按位异或运算实现历史局面的判断。

用途

Zobrist Hash算法是各类棋类程序中判断历史局面是否存在的算法。


算法基础

该算法的的基础利用了按位异或运算的如下性质:A^B^B = A


C++代码示例

// mersenne_twister_engine constructor  
#include <iostream>  
#include <chrono>  
#include <random>  
#include <list>

using namespace std;

int main()
{
	// obtain a seed from the system clock:  
	unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count();

	// obtain a seed from the user:  

	std::mt19937 g1(seed1);  // mt19937 is a standard mersenne_twister_engine  
	std::cout << "A time seed produced: " << g1() << std::endl;
	std::cout << typeid(g1()).name() << " sizeof(" << typeid(g1()).name() << ") = " << sizeof(g1()) << endl;

	list<unsigned> listInt;

	int current = 0;
	cout << "current=" << current << endl;

	for (int i = 0; i < 10; ++i)
	{
		int temp = g1();
		current ^= temp;
		listInt.push_back(temp);
		cout << "temp=" << temp << " current=" << current << endl;
	}
	cout << endl;
	for (auto itr = listInt.crbegin(); itr != listInt.crend(); ++itr)
	{
		int temp = *itr;
		cout << "temp=" << temp << " current=" << current << endl;
		current ^= temp;
	}
	cout << "current=" << current << endl;

	return 0;
}

运行结果


好的!我们将为五子棋 AI 添加 **Zobrist Hash + 转移表(Transposition Table)**,这是提升搜索效率的关键技术之一。 --- ## ✅ 功能说明 | 技术 | 作用 | |------|------| | Zobrist Hash | 用于唯一标识当前棋盘状态(快速计算哈希值) | | Transposition Table | 缓存已经搜索过的局面,避免重复计算 | --- ## 🧠 原理简述 - 每个位置(i, j)预先分配两个随机数:一个代表落黑子,一个代表落白子。 - 当在某个位置下子时,就异或对应位置的随机数来更新全局哈希值。 - 使用这个哈希值作为 key,将搜索结果缓存进转移表中。 - 下次遇到相同局面时直接取出结果,节省大量时间。 --- ## ✅ 修改后的完整代码(含 Zobrist Hash + Transposition Table) ### 🔧 添加全局变量和结构体定义 ```cpp #include <iostream> #include <vector> #include <limits> #include <cmath> #include <ctime> #include <map> #include <cstdlib> using namespace std; const int SIZE = 15; char board[SIZE][SIZE]; // 转移表条目类型 struct TTEntry { int depth; int score; bool isExact; }; map<unsigned long long, TTEntry> transTable; // 转移表 unsigned long long zobrist[SIZE][SIZE][2]; // Zobrist 哈希数组 unsigned long long currentHash = 0; // 当前棋盘哈希值 ``` --- ### 🔧 初始化 Zobrist 表 ```cpp void initZobrist() { srand((unsigned)time(0)); for (int i = 0; i < SIZE; ++i) for (int j = 0; j < SIZE; ++j) for (int k = 0; k < 2; ++k) zobrist[i][j][k] = ((unsigned long long)rand() << 48) ^ ((unsigned long long)rand() << 32) ^ ((unsigned long long)rand() << 16) ^ (unsigned long long)rand(); } // 更新当前哈希值 void updateHash(int x, int y, char player) { int index = (player == 'O'); // O: AI(玩家1),X: 玩家(玩家0) currentHash ^= zobrist[x][y][index]; } ``` --- ### 🔧 改写 `minimax()` 函数以支持转移表 ```cpp int minimax(int depth, int alpha, int beta, bool isMaximizing) { // 查找转移表 TTEntry entry; if (transTable.find(currentHash) != transTable.end()) { entry = transTable[currentHash]; if (entry.depth >= depth) { if (entry.isExact) return entry.score; else if (isMaximizing && entry.score >= beta) return beta; else if (!isMaximizing && entry.score <= alpha) return alpha; } } int score = evaluate(); if (score != 0 || depth == 4 || isFull()) { // 控制最大深度 return score; } int best; if (isMaximizing) { best = -numeric_limits<int>::max(); vector<pair<int, int> > candidates = getCandidateMoves(); sort(candidates.begin(), candidates.end(), moveCompare); for (auto move : candidates) { int i = move.first, j = move.second; if (board[i][j] == '.') { board[i][j] = 'O'; updateHash(i, j, 'O'); best = max(best, minimax(depth + 1, alpha, beta, false)); updateHash(i, j, 'O'); board[i][j] = '.'; alpha = max(alpha, best); if (beta <= alpha) break; } } } else { best = numeric_limits<int>::min(); vector<pair<int, int> > candidates = getCandidateMoves(); sort(candidates.begin(), candidates.end(), moveCompare); for (auto move : candidates) { int i = move.first, j = move.second; if (board[i][j] == '.') { board[i][j] = 'X'; updateHash(i, j, 'X'); best = min(best, minimax(depth + 1, alpha, beta, true)); updateHash(i, j, 'X'); board[i][j] = '.'; beta = min(beta, best); if (beta <= alpha) break; } } } // 存入转移表 TTEntry newEntry; newEntry.depth = depth; newEntry.score = best; newEntry.isExact = (best <= alpha ? false : (best >= beta ? false : true)); transTable[currentHash] = newEntry; return best; } ``` --- ### 🔧 修改 `findBestMove()` 中调用时清空 Hash ```cpp pair<int, int> findBestMove() { int bestVal = -numeric_limits<int>::max(); pair<int, int> bestMove = make_pair(-1, -1); vector<pair<int, int> > candidates = getCandidateMoves(); if (candidates.empty()) { for (int i = 0; i < SIZE; ++i) for (int j = 0; j < SIZE; ++j) if (board[i][j] == '.') candidates.push_back(make_pair(i, j)); } sort(candidates.begin(), candidates.end(), moveCompare); for (auto move : candidates) { int i = move.first, j = move.second; if (board[i][j] == '.') { board[i][j] = 'O'; updateHash(i, j, 'O'); int moveVal = minimax(0, -numeric_limits<int>::max(), numeric_limits<int>::max(), false); updateHash(i, j, 'O'); board[i][j] = '.'; if (moveVal > bestVal) { bestVal = moveVal; bestMove = move; } } } return bestMove; } ``` --- ### ✅ 完整主函数不变(略) 你可以使用之前完整的主函数逻辑,只需加入上述优化即可。 --- ## ✅ 总结效果 | 特性 | 效果 | |------|------| | Zobrist Hash | 快速生成棋盘唯一哈希 | | Transposition Table | 避免重复搜索相同局面 | | 启发式排序 | 加快剪枝触发 | | 局部区域搜索 | 大幅减少无效节点扩展 | ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

C++程序员Carea

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

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

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

打赏作者

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

抵扣说明:

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

余额充值