#include <math.h> #include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> using namespace std; #define N 20 int n, sum, x[N+1]; // n:问题规模 sum:方案数目 x[]方案存储 void Init() { cout << "输入皇后问题规模:"; cin >> n; sum = 0; memset(x, 0, sizeof(x)); } bool check(int row) { for(int i = 1; i < row; i++) { if(x[i]==x[row] || abs(x[row]-x[i])==abs(row-i)) return false; } return true; } void PrintResult() { cout << "方案" << ++sum << ":" << endl; for(int i = 1; i <= n; i++) { cout << x[i]; cout << (i==n) ? "\n" : " "; } } void Process(int row) { if(row > n) PrintResult(); for(int i = 1; i <= n; i++) { x[row] = i; if(check(row)) Process(row+1); } } int main() { Init(); Process(1); return 0; }