天天看點

n皇後問題遞歸算法C語言,【N皇後問題】遞歸算法

#include

#include

using namespace std;

const int maxn = 11;

int n,P[maxn],hashTable[maxn] = {false};

int count = 0;

void generateP(int index){

if(index == n + 1) {

bool flag = true;

for(int i = 1; i <= n;i++) {

for(int j = i + 1;j <= n;j++){

if(abs(i - j) == abs(P[i] - P[j])) {

flag = false;

}

}

}

if(flag)

count++;

return ;

}

for(int x = 1;x <= n;x++) {

if(hashTable[x] == false) {

P[index] = x;

hashTable[x] = true;

generateP(index + 1);

hashTable[x] = false;

}

}

}

int main(void){

cin >> n;

generateP(1);

cout << count;

return 0;

}

#include

#include

using namespace std;

const int maxn = 11;

int n,P[maxn],hashTable[maxn] = {false};

int count = 0;

void generateP(int index){

if(index == n + 1){

count ++;

return;

}

for(int x = 1;x <= n;x++){

if(hashTable[x] == false){

bool flag = true;

for(int pre = 1;pre < index;pre++){

if(abs(index - pre) == abs(x - P[pre])){

flag = false;

break;

}

}

if(flag){

P[index] = x;

hashTable[x] = true;

generateP(index + 1);

hashTable[x] = false;

}

}

}

}

int main(void){

cin >> n;

generateP(1);

cout << count;

return 0;

}