Run ID 作者 问题 语言 测评结果 时间 内存 代码长度 提交时间
86480 sh25_wangtaojie 八皇后问题 C++ 输出超限 3 MS 252 KB 1457 2026-04-03 14:56:42

Tests(0/1):


#include <iostream> #include <cstring> #include <cmath> using namespace std; const int N = 8; int col[8]; // 记录每一行皇后放在第几列 int ans[100][8]; // 存储所有答案 int total = 0; // 答案总数 // 检查第 row 行,第 c 列能不能放 bool check(int row, int c) { for (int i = 0; i < row; i++) { if (col[i] == c || abs(row - i) == abs(c - col[i])) return false; } return true; } // 回溯:从第0列开始尝试,保证顺序和样例一致 void dfs(int row) { if (row == 8) { // 保存答案 for (int i = 0; i < 8; i++) ans[total][i] = col[i]; total++; return; } // 关键:从 0 到 7 依次尝试,保证输出顺序和样例完全一样 for (int c = 0; c < 8; c++) { if (check(row, c)) { col[row] = c; dfs(row + 1); } } } int main() { memset(col, 0, sizeof(col)); dfs(0); // 输出所有解(8皇后一共92个,必须全部输出!) for (int k = 0; k < total; k++) { cout << "No. " << k + 1 << endl; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (ans[k][i] == j) cout << 1 << " "; else cout << 0 << " "; } cout << endl; } } return 0; }


测评信息: