题解:P3192 [HNOI2007] 胜负一子
这是一道经典的五子棋残局求解问题,主要考察博弈树搜索(Game Tree Search)、迭代加深搜索(IDDFS)以及启发式剪枝(Heuristic Pruning)。题目分析题目要求我们在一个
include <iostream>
include <vector>
include <algorithm>
using namespace std;
const int BOARD_SIZE = 15;
int board[BOARD_SIZE][BOARD_SIZE]; // 方向数组:横、竖、主对角、副对角
int dx[] = {0, 1, 1, 1};
int dy[] = {1, 0, 1, -1};
// 检查在 (x,y) 落子 color 后是否直接获胜
bool check_win(int x, int y, int color) {
// ... 常规连五检测逻辑 ...
}
// 评估并生成候选点(按照威胁程度排序)
vector<pair<int, int>> generate_moves(int color) {
vector<pair<int, int>> moves;
// 1. 检查己方是否有直接成五的点
// 2. 检查对方是否有将成五的点(必须堵)
// 3. 提取已有棋子周围半径 2 以内的空点并评分排序
return moves;
}
// 与或树搜索:当前是否黑棋走,剩余深度 limit
bool dfs(int limit, bool is_black, pair<int, int>& first_move) {
if (limit == 0) return false;
int color = is_black ? 1 : 2;
vector<pair<int, int>> moves = generate_moves(color);
if (is_black) {
// OR 节点:黑棋只要有一种走法必胜即可
for (auto p : moves) {
board[p.first][p.second] = 1;
if (check_win(p.first, p.second, 1)) {
board[p.first][p.second] = 0;
return true;
}
bool can_win = dfs(limit - 1, false, first_move);
board[p.first][p.second] = 0;
if (can_win) {
return true;
}
}
return false;
} else {
// AND 节点:白棋的所有合理防守走法,黑棋都能赢
// 如果白棋没有合法走法,或者白棋有一步能直接赢,黑棋失败
for (auto p : moves) {
board[p.first][p.second] = 2;
if (check_win(p.first, p.second, 2)) {
board[p.first][p.second] = 0;
return false; // 白棋赢了,这条路黑棋无法必胜
}
bool can_win = dfs(limit - 1, true, first_move);
board[p.first][p.second] = 0;
if (!can_win) {
return false; // 白棋找到了防御方法
}
}
return true;
}
}
int main() {
// 1. 读取棋盘
for (int i = 0; i < BOARD_SIZE; ++i) {
for (int j = 0; j < BOARD_SIZE; ++j) {
cin >> board[i][j];
}
}
// 2. 迭代加深搜索
int ans_depth = -1;
vector<pair<int, int>> winning_moves;
for (int depth = 1; depth <= 11; depth += 2) {
vector<pair<int, int>> black_moves = generate_moves(1);
for (auto p : black_moves) {
board[p.first][p.second] = 1;
if (check_win(p.first, p.second, 1) || dfs(depth - 1, false, p)) {
winning_moves.push_back(p);
}
board[p.first][p.second] = 0;
}
if (!winning_moves.empty()) {
ans_depth = depth;
break;
}
}
// 3. 排序并输出结果
if (ans_depth != -1) {
// 按 15 * i + j 从小到大排序
sort(winning_moves.begin(), winning_moves.end(), [](const pair<int,int>& a, const pair<int,int>& b) {
return a.first * BOARD_SIZE + a.second < b.first * BOARD_SIZE + b.second;
});
cout << ans_depth << " " << winning_moves.size() << endl;
for (auto p : winning_moves) {
cout << p.first << " " << p.second << endl; // 注意题目下标可能是从0还是从1开始的,视情况+1
}
}
return 0;
}
注意事项坐标系与排序:题目要求坐标按