递归——全排序 & 八皇后

1.全排序问题

例:输出{1,2,3}的全排序

#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXSIZE=11;
int count=0;
int n,P[MAXSIZE];
bool hashTable[MAXSIZE]={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(){
    n=3;
    generateP(1);
    return 0;

}

2.八皇后问题

(1)暴力法:如上全排序问题,判断每一种情况是否合法

#include <cstdio>
#include <algorithm>
using namespace std;

const int MAXSIZE=10;
int P[MAXSIZE];
bool hashTable[MAXSIZE]={false};
int n;
int cnt=0;

void generateP(int index){
    if(index==n+1){
        bool flag=false;    //判断是否互斥,即没有同行。同列,同队
        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=true;
                    break;
                }
            }
        }
        if(!flag)    cnt++;   //如果不互斥,则方案+1
        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(){
    n=8;
    generateP(1);
    printf("%d",cnt);
    return 0;

}

(2)优化算法——回溯法

#include <cstdio>
#include <algorithm>
using namespace std;

const int MAXSIZE=10;
int P[MAXSIZE];
bool hashTable[MAXSIZE]={false};
int n;
int cnt=0;

void generateP(int index){
    if(index==n+1){
        cnt++;
        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(){
    n=8;
    generateP(1);
    printf("%d",cnt);
    return 0;

}

总结:递归问题....开始学很简单,现在觉得好难啊,八皇后问题还是不怎么明白,理解个大概.......如果各位有啥好的理解方式,望评论见!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值