提交时间:2026-04-03 14:58:19
运行 ID: 86482
#include <iostream> using namespace std; // 棋盘:8x8,初始全0 int board[8][8] = {0}; // 记录每一列是否有皇后 int col[8] = {0}; // 记录主对角线(左上→右下)是否有皇后 int dia1[15] = {0}; // 记录副对角线(右上→左下)是否有皇后 int dia2[15] = {0}; // 记录解的编号 int cnt = 0; // 深度优先搜索:放置第row行的皇后 void dfs(int row) { // 8行都放置完毕,找到一个解 if (row == 8) { cnt++; // 输出格式 cout << "No. " << cnt << endl; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { cout << board[i][j] << " "; } cout << endl; } return; } // 尝试在当前行的每一列放置皇后 for (int c = 0; c < 8; c++) { // 计算对角线索引 int d1 = row - c + 7; int d2 = row + c; // 判断当前位置是否可以放置 if (!col[c] && !dia1[d1] && !dia2[d2]) { // 放置皇后 board[row][c] = 1; col[c] = 1; dia1[d1] = 1; dia2[d2] = 1; // 递归下一行 dfs(row + 1); // 回溯:撤销操作 board[row][c] = 0; col[c] = 0; dia1[d1] = 0; dia2[d2] = 0; } } } int main() { // 从第0行开始搜索 dfs(0); return 0; }