回溯法解N皇后

描述

使用回溯技术改进递归算法,边递归边进行check。

请你统计N皇后问题解的数量。

输入

一个正整数N(N <= 13)

输出

1个整数,代表N皇后问题解的数量;若无解,输出“No Solution!”。

样例输入

8

样例输出

92

提示

* 虽说回溯法相对于朴素枚举来说是一个很大改进,但是并不能降低复杂度(还是指数的),对于较大的N(>15)仍然无能为力。对于这种情况我们称为常数优化,即缩小了T(N)中的常数c。

// Created on 2020/2/10

#include <bits/stdc++.h>

using namespace std;

//int i,j,k;

const int maxn=INT_MAX;

const int idata=50;
int judge[idata][3];
int n,m;
int cnt;

void dfs(int x)
{
    for(int i=1;i<=n;i++)
    {
        if(!judge[i][0]&&!judge[x+i][1]&&!judge[i-x+13][2])
        {
            judge[i][0]=1;
            judge[x+i][1]=1;
            judge[i-x+13][2]=1;

            if(x==n) cnt++;
            else dfs(x+1);

            judge[i][0]=0;
            judge[x+i][1]=0;
            judge[i-x+13][2]=0;
        }
    }
}

int main()
{
    cin>>n;
    dfs(1);
    if(cnt)
        cout<<cnt<<endl;
    else
        cout<<"No Solution!"<<endl;
    return 0;
}
发布了177 篇原创文章 · 获赞 8 · 访问量 6342

猜你喜欢

转载自blog.csdn.net/C_Dreamy/article/details/104247341