一、用全排列体会递归思想
#include <iostream>
using namespace std;
const int maxn = 10;
int n, P[maxn], hashTable[maxn] = {}; //P为当前排列,hashTable记录整数x是否已在P中用过
void generateP(int index){ //当前处理第index位数字
if(index == n + 1){ //递归边界,当前已处理完1~n位数字
for(int i = 1; i <= n; i++){ //输出当前的排列P
cout << P[i];
}
cout << endl;
return ;
}
for(int x = 1; x <= n; x++){ //枚举1~n,试图将x填入P[index]
if(hashTable[x] == false){ //如果x在P中未使用过
P[index] = x; //将x填入P[index],即把x加入当前排列
hashTable[x] = true; //标记x已被使用
generateP(index + 1); //接下来递归处理P[index + 1],即下一个位置
hashTable[x] = false; //处理完当前排列后,return回来的时候将hashTable数组还原状态。
}
}
}
int main(){
cin >> n;
generateP(1); //从P[1]开始填数字
return 0;
}
二、n皇后问题
n皇后问题就是在一张n*n的棋盘上放置n个皇后,使得这n个皇后两两不在同一行、同一列、同一对角线上,求合法方案的个数。
将此问题抽象为数学模型,每一行每一列只能放置一个皇后,转化为上面的全排列问题,棋盘的列数i
作为P数组的下标,其值P[i]
为该列皇后所在的行号,只需要在每次生成一个全排列的时候判断是否合法即可。此方法为暴力法。
#include <iostream>
using namespace std;
const int maxn = 10;
int n, P[maxn], hashTable[maxn] = {};
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(){
cin >> n;
generateP(1); //从P[1]开始填数字
return 0;
}
可以对上述暴力方法进行优化。如果在递归某层发现已经不符合题意,那么无需继续递归下去直到递归边界,可以提前结束此次递归直接return。这种方法叫做回溯法。
#include <iostream>
using namespace std;
const int maxn = 10;
int n, P[maxn], hashTable[maxn] = {};
int count = 0;
void generateP(int index){
if(index == n + 1){
count++; //能够到达递归边界的肯定是合法方案
return;
}
for(int x = 1; x <= n; x++){
if(hashTable[x] == false){ //如果第x行还没有皇后
bool flag = true; //标记当前皇后放在第x行是否与之前的皇后有冲突
for(int pre = 1; pre < index; pre++){ //遍历之前的皇后
if(abs(pre - index) == abs(P[pre] - x)){//index为当前皇后的列号,pre为之前皇后的列号;x为当前皇后的行号,P[pre]为之前皇后的行号
flag = false;
break;
}
}
if(flag){
P[index] = x;
hashTable[x] = true;
generateP(index + 1);
hashTable[x] = false;
}
}
}
}
int main(){
cout << "请输入棋盘的大小:n = ";
cin >> n;
generateP(1); //从P[1]开始填数字
cout << "合法的方案有:" << count << "种。\n";
return 0;
}