全排列问题
#include<stdio.h>
const int maxn = 11;
int n,P[maxn],hashTable[maxn] = {false};
void generateP(int index){
if(index == n+1){
for(int i = 1;i<=n;i++){
printf("%d",P[i]);
}
printf("\n");
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){
n = 3;
generateP(1);
return 0;
}
推演:
hashtable = false
n = 3
generateP(1):
index = 1
if(index == n+1)不满足
for:
x = 1
if(hashTable[x] == false)满足:
P[1] = 1
hashTable[1] = true
generateP(2):
index = 2
if(index == n+1)不满足
for:
x = 1
if(hashTable[x] == false)不满足
x = 2
if(hashTable[x] == false)满足:
P[2] = 2
hashTable[2] = true
generateP(3):
index = 3
if(index == n+1)不满足
for:
x = 1
if(hashTable[x] == false)不满足
x = 2
if(hashTable[x] == false)不满足
x = 3
if(hashTable[x] == false)满足:
P[3] = 3
hashTable[3] = true
generateP(4):
if(index == n+1)满足:
输出:123
hashTable[3] = false
hashTable[2] = false
x = 3
if(hashTable[x] == false)满足:
P[2] = 3
hashTable[3] = true
generateP(3):
index = 3
if(index == n+1)不满足
for:
x = 1
if(hashTable[x] == false)不满足
x = 2
if(hashTable[x] == false)满足:
P[3] = 2
hashTable[2] = true
generateP(4):
if(index == n+1)满足:
输出:132
hashTable[2] = false
x = 3
if(hashTable[x] == false)不满足
hashTable[3] = false
hashTable[1] = false
x = 2
......
八皇后问题:
#include<stdio.h>
#include<math.h>
const int maxn = 11;
int count = 0;
int n,P[maxn],hashTable[maxn] = {false};
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){
n = 8;
generateP(1);
printf("%d",count);
return 0;
}