版本比较
沙博弈算法
正文
增加 88 行删除 88 行
96 行未改动9798991001011011021031041052 行未改动1081091101111121121131141151151161171181191201201211221231231241251261261271281291301311311321331341351351361371381381391401411411421431441451451461471471481491501511511521531541551561571581591601601611621631641651651661671681691701701711721731743 行未改动17817918018118218218318418518618718818918919019119219219319419519611 行未改动2082092102112122122132142152163 行未改动2202212222232242242252262272284 行未改动2332342352362372372382392402412422432432442452452462472482492492502512522532542552562572572582592602612612622632642652662662672682692702 行未改动2732742752762772772782792802812822832832842852862872882882892902912912922932942952962962972982993003013013023033043053063073073083093093103113123133143153153163173183183193203213213223233243243253263273283293303313313323333343353363363373383393403403413423433443443453463473473483493503513523533543543553563573583593603613623633633643653663679 行未改动3773783793803813813823833843854 行未改动3903913923933943943953963973984 行未改动4034044054064074074084094104114114124134144154154164174184194204214214224234244254264274274284294294304314324333 行未改动4374384394404414414424434444454464464474484494504514514524534544554554564574584584594604614614624634644654664674684684694704714724724734744754764774774784794804817 行未改动4894904914924934934944954964974984995005015015025035045054 行未改动5105115125135145145155165175185195205215225235235245255265277 行未改动5355365375385395395405415425425435445455465475475485495505515525535545555565575575585595595605615625635635645655665675685685695705715715725735745755765775785795805805815825835845855865865875885895903 行未改动59459559659759859859960060160260360360460560660760760860961061161261361361461561661761861861962062162262362362462562662762862963063163163263363463563663663763863963964064164264364464464564664764838 行未改动96 行未改动private: int rows, cols; vector<vector<int>> grid; const int CRITICAL = 4; // 临界值,通常为4
// 将状态编码为字符串(用于哈希) string encodeState() const { string code; for (int i = 0; i < rows; i++) {2 行未改动 } } return code; }
public: SandPile2D(int r, int c) : rows(r), cols(c), grid(r, vector<int>(c, 0)) {}
SandPile2D(const vector<vector<int>>& init) : grid(init) { rows = grid.size(); if (rows > 0) cols = grid[0].size(); }
// 获取当前状态 vector<vector<int>> getState() const { return grid; }
// 设置状态 void setState(const vector<vector<int>>& newState) { grid = newState; }
// 判断行动是否安全(不会引发溢出) bool isMoveSafe(int r, int c) { if (r < 0 || r >= rows || c < 0 || c >= cols) return false; if (grid[r][c] >= CRITICAL - 1) return false; // 放入就会溢出
// 模拟放置,检查是否会引发连锁溢出 vector<vector<int>> temp = grid; temp[r][c]++;
// 检查是否会立即溢出 if (temp[r][c] >= CRITICAL) return false;
return true; }
// 模拟放置沙晶(返回是否安全) bool makeMove(int r, int c) { if (!isMoveSafe(r, c)) return false;
grid[r][c]++;
// 检查并处理溢出(连锁反应) bool overflow = false; queue<pair<int, int>> q;
// 初始检查 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (grid[i][j] >= CRITICAL) { q.push({i, j}); } } }
// 处理连锁溢出 while (!q.empty()) { auto [i, j] = q.front(); q.pop();
if (grid[i][j] >= CRITICAL) { overflow = true; int overflowCount = grid[i][j] / CRITICAL; grid[i][j] %= CRITICAL;
// 向四个方向分配 vector<pair<int, int>> directions = {{-1,0},{1,0},{0,-1},{0,1}}; for (auto [di, dj] : directions) { int ni = i + di, nj = j + dj;3 行未改动 q.push({ni, nj}); } } }
// 重新检查当前格子(可能再次溢出) if (grid[i][j] >= CRITICAL) { q.push({i, j}); } } }
return !overflow; }
// 显示棋盘 void display() const { cout << "当前棋盘状态:" << endl; for (int i = 0; i < rows; i++) {11 行未改动
class SandGameSolver2D {private: unordered_map<string, bool> memo; // 记忆化缓存
// 状态编码 string encode(const vector<vector<int>>& state) { string code; int rows = state.size(), cols = state[0].size();3 行未改动 } } return code; }
// 检查是否还有安全行动 bool hasSafeMove(const vector<vector<int>>& state) { int rows = state.size(), cols = state[0].size(); for (int i = 0; i < rows; i++) {4 行未改动 } } return false; }
// 模拟放置沙晶(不修改原状态) vector<vector<int>> simulateMove(const vector<vector<int>>& state, int r, int c) { vector<vector<int>> newState = state; int rows = state.size(), cols = state[0].size(); const int CRITICAL = 4;
newState[r][c]++;
// 处理溢出 bool overflow = false; queue<pair<int, int>> q;
for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (newState[i][j] >= CRITICAL) { q.push({i, j}); } } }
while (!q.empty()) { auto [i, j] = q.front(); q.pop();
if (newState[i][j] >= CRITICAL) { overflow = true; int overflowCount = newState[i][j] / CRITICAL; newState[i][j] %= CRITICAL;
vector<pair<int, int>> dirs = {{-1,0},{1,0},{0,-1},{0,1}}; for (auto [di, dj] : dirs) { int ni = i + di, nj = j + dj; if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) {2 行未改动 q.push({ni, nj}); } } }
if (newState[i][j] >= CRITICAL) { q.push({i, j}); } } }
// 如果有溢出,返回空状态(表示行动失败) if (overflow) { return {}; }
return newState; }
public: // 判断当前状态是否先手必胜 bool isFirstPlayerWinning(const vector<vector<int>>& state) { string code = encode(state);
// 检查缓存 if (memo.find(code) != memo.end()) { return memo[code]; }
// 如果没有安全行动,先手必败 if (!hasSafeMove(state)) { memo[code] = false; return false; }
int rows = state.size(), cols = state[0].size();
// 尝试所有可能的行动 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { // 只能选择沙晶数 ≤ 2 的格子 if (state[i][j] > 2) continue;
// 模拟行动 vector<vector<int>> newState = simulateMove(state, i, j);
// 如果行动导致溢出,跳过 if (newState.empty()) continue;
// 递归判断对手是否必败 bool opponentLoses = !isFirstPlayerWinning(newState);
if (opponentLoses) { memo[code] = true; return true; } } }
// 所有行动都导致对手必胜,则先手必败 memo[code] = false; return false; }
// 寻找最优行动(如果存在必胜策略) pair<int, int> findOptimalMove(const vector<vector<int>>& state) { int rows = state.size(), cols = state[0].size();
for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (state[i][j] > 2) continue;
vector<vector<int>> newState = simulateMove(state, i, j); if (newState.empty()) continue;
bool opponentLoses = !isFirstPlayerWinning(newState); if (opponentLoses) { return {i, j}; } } }
// 没有必胜策略,返回第一个安全行动 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (state[i][j] <= 2) { return {i, j}; } } }
return {-1, -1}; // 无安全行动 }};
9 行未改动private: // 状态压缩:每个格子用2位表示(0-3),共需要2*m*n位 int rows, cols; unordered_map<long long, bool> winTable; // 胜负表
// 状态编码 long long encodeState(const vector<vector<int>>& state) { long long code = 0; int pos = 0;4 行未改动 } } return code; }
// 状态解码 vector<vector<int>> decodeState(long long code) { vector<vector<int>> state(rows, vector<int>(cols, 0)); int pos = 0;4 行未改动 } } return state; }
// 预计算所有状态的胜负 void precompute() { int totalStates = 1 << (2 * rows * cols); // 4^(rows*cols)
// 由于状态数可能很大,我们使用动态规划从终态开始计算 vector<bool> visited(totalStates, false); vector<bool> winning(totalStates, false);
// 从所有状态开始计算 for (long long stateCode = 0; stateCode < totalStates; stateCode++) { compute(stateCode); } }
// 递归计算一个状态的胜负 bool compute(long long stateCode) { if (winTable.find(stateCode) != winTable.end()) { return winTable[stateCode]; }
vector<vector<int>> state = decodeState(stateCode);
// 检查是否有安全行动 bool hasSafe = false; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) {3 行未改动 } } if (hasSafe) break; }
if (!hasSafe) { winTable[stateCode] = false; return false; }
// 尝试所有行动 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (state[i][j] > 2) continue;
// 模拟行动 vector<vector<int>> newState = state; newState[i][j]++;
// 检查是否溢出 if (newState[i][j] >= 4) continue;
long long newCode = encodeState(newState); bool opponentLoses = !compute(newCode);
if (opponentLoses) { winTable[stateCode] = true; return true; } } }
winTable[stateCode] = false; return false; }
public: SmallBoardSolver(int r, int c) : rows(r), cols(c) { precompute(); }
bool isWinning(const vector<vector<int>>& state) { long long code = encodeState(state); return winTable[code]; }7 行未改动private: // 评估函数:基于多个启发式规则 double evaluatePosition(const vector<vector<int>>& state) { int rows = state.size(), cols = state[0].size();
// 启发式1:角落控制(角落位置更容易防守) double cornerScore = 0; cornerScore += (state[0][0] == 3) ? -1 : (3 - state[0][0]) * 0.5; cornerScore += (state[0][cols-1] == 3) ? -1 : (3 - state[0][cols-1]) * 0.5; cornerScore += (state[rows-1][0] == 3) ? -1 : (3 - state[rows-1][0]) * 0.5; cornerScore += (state[rows-1][cols-1] == 3) ? -1 : (3 - state[rows-1][cols-1]) * 0.5; cornerScore /= 4.0;
// 启发式2:边缘控制 double edgeScore = 0; int edgeCount = 0; for (int i = 0; i < rows; i++) {4 行未改动 } } } edgeScore /= max(edgeCount, 1);
// 启发式3:危险格子数(值为3的格子) int dangerCount = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (state[i][j] == 3) dangerCount++; } } double dangerScore = -dangerCount * 0.2;
// 启发式4:对称性(对称棋盘通常对先手有利) double symmetryScore = 0; if (rows == cols) { bool symmetric = true;7 行未改动 if (!symmetric) break; } if (symmetric) symmetryScore = 0.1; }
return cornerScore + edgeScore + dangerScore + symmetryScore; }
public: // 蒙特卡洛树搜索的简化版本 pair<int, int> findBestMove(const vector<vector<int>>& state, int simulations = 1000) { int rows = state.size(), cols = state[0].size();
// 收集所有安全行动 vector<pair<int, int>> safeMoves; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (state[i][j] <= 2) { safeMoves.push_back({i, j}); } } }
if (safeMoves.empty()) return {-1, -1};
// 对每个行动进行简单评估 pair<int, int> bestMove = safeMoves[0]; double bestScore = -1e9;
for (auto [r, c] : safeMoves) { // 模拟行动 vector<vector<int>> newState = state; newState[r][c]++;
// 评估新状态 double score = evaluatePosition(newState);
// 额外加分:如果行动后不会给对手留下危险位置 int newDanger = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (newState[i][j] == 3) newDanger++; } } score -= newDanger * 0.1;
if (score > bestScore) { bestScore = score; bestMove = {r, c}; } }
return bestMove; }};
3 行未改动
int main() { cout << "二维沙博弈算法测试" << endl; cout << "==================" << endl;
// 测试1:2×2棋盘 { cout << "\n测试1:2×2棋盘,初始全0" << endl; vector<vector<int>> state = {{0, 0}, {0, 0}};
SandGameSolver2D solver; bool winning = solver.isFirstPlayerWinning(state); cout << "先手必胜: " << (winning ? "是" : "否") << endl;
if (winning) { auto move = solver.findOptimalMove(state); cout << "最优行动: (" << move.first << ", " << move.second << ")" << endl; } }
// 测试2:3×3棋盘 { cout << "\n测试2:3×3棋盘,初始全0" << endl; vector<vector<int>> state = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
// 由于3×3状态空间较大,我们使用启发式求解器 HeuristicSolver heuristicSolver; auto move = heuristicSolver.findBestMove(state, 500); cout << "启发式推荐行动: (" << move.first << ", " << move.second << ")" << endl;
// 小棋盘可以使用精确求解器 if (state.size() <= 3 && state[0].size() <= 3) { SmallBoardSolver exactSolver(3, 3); bool winning = exactSolver.isWinning(state); cout << "精确解(先手必胜): " << (winning ? "是" : "否") << endl; } }
// 测试3:特定状态分析 { cout << "\n测试3:特定状态分析" << endl; vector<vector<int>> state = {{3, 2, 1}, {2, 1, 0}, {1, 0, 0}};
SandPile2D game(state); game.display();
SandGameSolver2D solver; bool winning = solver.isFirstPlayerWinning(state); cout << "先手必胜: " << (winning ? "是" : "否") << endl; }
return 0;}```
38 行未改动