八皇后问题

#include<iostream>
#include<math.h>
using namespace std;

int n = 8;
int total = 0;
int *c = new int(n); //也可以写为int c[n];表示皇后放在第几列

bool check(int curRow)
{
    //放当前行的皇后时,只需要检查跟前面那些行的皇后有没有冲突
    //不需要考虑后几行,因为后几行的皇后还没放上去呢
    for(int preRow = 0; preRow != curRow; preRow++)
    {
        if(c[curRow] == c[preRow] ||
           curRow - c[curRow] == preRow - c[preRow] ||
           curRow + c[curRow] == preRow + c[preRow])
        {
            return false;
        }
    }

    return true;
}

void queen(int row)
{
    if(row == n)
    {
        // 从0到n-1行,全部都已经放上皇后了,所以答案+1
        total++;

        // 打印出n个皇后具体放在0~n-1行的第几列
        for(int i = 0; i<n; i++)
        {
            cout << c[i] << " ";
        }
        cout << endl;
    }
    else
    {
        for(int col = 0; col != n; col++)
        {
            c[row] = col;
            if(check(row))
            {
                queen(row + 1);
            }
        }
    }
}

int main()
{
    queen(0);
    cout << total << endl;
    
    return 0;
}
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<math.h>
using namespace std;
int n,i;//n记录是多少个皇后的问题,i记录的是第几个皇后 
int a[101];//数组下标表示行号,数组值表示列号 
int sum;//记录有多少种解法 
bool judge(int a[],int N) //检测当前位置的皇后是否是合法的 
{  
    for(int j=1;j<N;j++)  
    {  
        if(abs(a[j]-a[N])==abs(j-N) || a[j]==a[N])//见下面注释  
            return false;  
    }  
    return true;  
}  
void print_ans(){//打印输出每一种解的方案。 
    for(int j=1;j<=n;j++)
        cout<<"<"<<j<<","<<a[j]<<">"<<"   ";
    cout<<endl; 
} 
void solve(int i){//使用该函数来实现递归检测八皇后合法性
    if(i>n){//递归出口,每出现一次,意味着得到了一种解 
        sum++; 
        print_ans();//输出答案; 
        return ;
    } 
    for(int j=1;j<=n;j++){//每一行8列都尝试走一遍 
        a[i]=j;
        if(judge(a,i)){//判断当前皇后是否满足要求,满足则递归至下一层 
            solve(i+1);
        }            
    }
}
int main(){
    cin>>n;
    sum=0; 
    solve(1);//
    cout<<"一共有多少组解:"<<sum; 
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值