n皇后问题

本文介绍了一种使用回溯法求解N皇后问题的C++实现方案。通过递归搜索并放置皇后,确保任意两个皇后不在同一行、列及斜线上。代码实现了状态的保存、检查和撤销,展示了解决N皇后问题的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用回溯法解决

q[i]表示第i行皇后所在的列下标

#include <iostream>

using namespace std;

void search(int *p , int n , int cur , int* count , int*  node){
    (*node)++ ;
    if(cur == n ){
        (*count)++;
        cout<<*count<<"th solution:"<<endl ;
        for(int i=0 ; i != n ; i++)
            cout<<p[i]<<" "<<flush ;
        cout<<endl ;
        return ;
    }
    for(int i = 0 ; i != n ; i++){
        p[cur] = i ;
        int ok = 1 ;
        for(int j = 0 ; j != cur ; j++)
            if(p[j] == p[cur] || j+p[j] == cur+p[cur] || j-p[j] == cur - p[cur]){
                ok = 0 ;
                break ;
            }
        if(ok == 1 )
            search( p , n , cur+1,count , node) ;
    }
}

int n_queen( int n , int* node ){
    int* p = new int[n] ;
    int count = 0 ;
    int *q = &count ;
    search(p , n , 0 , q , node) ;
    delete[] p ;
    return count ;
}

int main()
{

    int n ;
    int m ;
    int *node = &m ;
    cout<<"input n : "<< flush ;
    while(cin>>n){
        m = 0 ;
        if(n<2)
            cout<<" n should not less than 2 "<<endl;
            else{
                cout<<"the count of "<<n<<" queens problem's solution is : "<<n_queen(n ,node )<<endl ;
                cout<<"the count of "<<n<<" queens problem's nodes is : "<<m<<endl ;
        }

        cout<<"input n : "<< flush ;
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值