n皇后问题and优化

版权声明:转就转吧~~记得声明噢~~ https://blog.csdn.net/Soul_97/article/details/82685546

普通写法:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 105;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;

int a[15];
int n, ans;

void dfs(int step)
{
    if(step == n + 1){
        ans ++;
        if(ans <= 3){
            for(int i = 1;i <= n;i ++){
                if(i != 1)
                    cout << " ";
                cout << a[i];
            }
            cout << '\n';
        }
        return ;
    }

    for(int i = 1;i <= n;i ++){

        int j;

        for(j = 1;j < step;j ++){

            if(i == a[j] || abs(step - j) == abs(a[j] - i))
                break;
        }

        if(j == step){
            a[step] = i;
            dfs(step+1);
        }
    }
}

int main()
{
    cin >> n;

    dfs(1);

    cout << ans << endl;
    return 0;
}

回溯优化写法:

使用数组标记,对于每一个点 行,列,两条对角线保证只有一个棋子

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 105;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;

int a[15], b[3][50];
int n, ans;

void dfs(int step)
{
    if(step >= n + 1){
        ans ++;
        if(ans <= 3){
            for(int i = 1;i <= n;i ++){
                if(i != 1)
                    cout << " ";
                cout << a[i];
            }
            cout << '\n';
        }
        return ;
    }

    for(int i = 1;i <= n;i ++){

        if(!b[0][i] && !b[1][step+i] && !b[2][step-i+n]){

            a[step] = i;
            b[0][i] = b[1][step+i] = b[2][step-i+n] = 1;
            dfs(step+1);
            b[0][i] = b[1][step+i] = b[2][step-i+n] = 0;
        }
    }
}

int main()
{
    cin >> n;

    dfs(1);

    cout << ans << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Soul_97/article/details/82685546
今日推荐