算法复习 DFS两题

全排列 模版题 AcWing 842. 排列数字

#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <stack>

using namespace std;
typedef long long ll;
typedef pair<int, int>P;
const int maxn = 1e5 + 10;
const int INF = 0x3f3f3f3f;
const ll mod = 998244353;
const double eps = 1e-11;
const double pi = 3.141592653;

bool rec[10];
int n;
vector<int> v;
void dfs(int h)
{
    if(h == n+1)
    {
        for(int j = 0; j < n; ++j) cout << v[j] << " \n"[j==n-1];
        return;
    }
    for(int i = 1; i <= n; ++i)
    {
        if(rec[i] == 0)
        {
            rec[i] = 1;
            v.push_back(i);
            dfs(h + 1);
            v.pop_back();
            rec[i] = 0;
        }
    }
}

int main()
{
    cin >> n;
    dfs(1);
}

n-皇后 剪枝 AcWing 843. n-皇后问题

#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <stack>

using namespace std;
typedef long long ll;
typedef pair<int, int>P;
const int maxn = 1e5 + 10;
const int INF = 0x3f3f3f3f;
const ll mod = 998244353;
const double eps = 1e-11;
const double pi = 3.141592653;

int n;

bool y[10], u[20], v[20];
vector<int> vec;
int tot;
void dfs(int h)
{
    if(h == n + 1)
    {
        tot++;
        if(tot != 1) cout << endl;
        for(int i = 0; i < n; ++i)
        {
            for(int j = 1; j <= n; ++j)
            {
                if(j != vec[i]) cout << ".";
                else cout << "Q";
            }
            cout << endl;
        }
        return;
    }
    for(int i = 1; i <= n; ++i)
    {
        if(!y[i] && !u[h+i] && !v[h+n+1-i])
        {
            //cout << h << ' ' << i << endl;
            y[i] = 1;
            u[h+i] = 1;
            v[h+n+1-i] = 1;
            vec.push_back(i);
            dfs(h+1);
            y[i] = 0;
            u[h+i] = 0;
            v[h+n+1-i] = 0;
            vec.pop_back();
        }
    }

}

int main()
{
    cin >> n;
    dfs(1);
}
posted @ 2023-12-24 06:16  .Ivorelectra  阅读(2)  评论(0编辑  收藏  举报