回溯法:
#include<iostream>
using namespace std;
int solve[100];
int count = 0, N;
void PrintSolve(){
cout << count << ':';
for(int i = 0; i < N; i++)
cout << ' ' << solve[i];
cout << endl;
}
void PutQueen(int step){
for(int j = 0; j < N; j++){
solve[step] = j;
int flag = 1;
for(int k = 0; k < step; k++){
if(solve[k] == j || abs(step - k) == abs(solve[k] - j))
flag = 0;
}
if(flag == 1){
if(step == N - 1){
PrintSolve();
count++;
return ;
}else{
PutQueen(step + 1);
}
}
}
}
int main(){
cout << "Please input the number of rows:" << endl;
cin >> N;
PutQueen(0);
return 0;
}