题解:P3192 [HNOI2007] 胜负一子
写出来的人一定开挂了
根本不对,仅供参考:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int BOARD_SIZE = 15;
const int DIRECTIONS[4][2] = {{1, 0}, {0, 1}, {1, 1}, {1, -1}}; // 四个检查方向:水平、垂直、对角线
struct Move {
int row;
int col;
bool operator<(const Move& other) const {
return BOARD_SIZE * row + col < BOARD_SIZE * other.row + other.col;
}
};
vector<vector<int>> board(BOARD_SIZE, vector<int>(BOARD_SIZE));
// 检查某个位置是否形成五连
bool checkWin(int row, int col, int player) {
for (const auto& dir : DIRECTIONS) {
int count = 1;
// 正向检查
for (int i = 1; i < 5; i++) {
int r = row + dir[0] * i;
int c = col + dir[1] * i;
if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE || board[r][c] != player)
break;
count++;
}
// 反向检查
for (int i = 1; i < 5; i++) {
int r = row - dir[0] * i;
int c = col - dir[1] * i;
if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE || board[r][c] != player)
break;
count++;
}
if (count >= 5) return true;
}
return false;
}
// 递归搜索获胜的最少步数
void findWinningMoves(int stepsLeft, vector<Move>& currentPath,
vector<vector<Move>>& solutions, int& minSteps) {
if (stepsLeft <= 0) return;
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == 0) { // 空位
board[i][j] = 1; // 黑棋落子
currentPath.push_back({i, j});
if (checkWin(i, j, 1)) { // 检查是否获胜
if (stepsLeft < minSteps) {
minSteps = stepsLeft;
solutions.clear();
solutions.push_back(currentPath);
} else if (stepsLeft == minSteps) {
solutions.push_back(currentPath);
}
} else {
findWinningMoves(stepsLeft - 1, currentPath, solutions, minSteps);
}
currentPath.pop_back();
board[i][j] = 0; // 回溯
}
}
}
}
int main() {
// 读取棋盘状态
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
cin >> board[i][j];
}
}
int minSteps = 5; // 最多需要4步(因为题目要求最少步数)
vector<vector<Move>> solutions;
vector<Move> currentPath;
// 搜索1-4步内的获胜可能
for (int steps = 1; steps <= 4; steps++) {
findWinningMoves(steps, currentPath, solutions, minSteps);
if (!solutions.empty()) break; // 找到最少步数就停止
}
// 处理结果
if (solutions.empty()) {
cout << "0 0" << endl; // 没有获胜可能
} else {
// 收集所有第一步走法
vector<Move> firstMoves;
for (const auto& path : solutions) {
firstMoves.push_back(path[0]);
}
// 去重并排序
sort(firstMoves.begin(), firstMoves.end());
firstMoves.erase(unique(firstMoves.begin(), firstMoves.end()), firstMoves.end());
// 输出结果
cout << minSteps << " " << firstMoves.size() << endl;
for (const auto& move : firstMoves) {
cout << move.row + 1 << " " << move.col + 1 << endl; // 转换为1-based索引
}
}
return 0;
}//大慈大悲的管理员,让我过吧🙏
谁抄谁废物😁
要死一起死,我写的也不对。