排列数字题目链接

842. 排列数字 - AcWing题库

排列数字题目类型

dps

排列数字代码

#include<iostream>

using namespace std;

const int N = 10;

int n;
int path[N];
bool st[N];
void dfs(int u)
{
    if(u==n)
    {
        for(int i=0;i<n;i++)  printf("%d ",path[i]+1);
        puts("");
        return ;
    }
    
    for(int i=0;i<n;i++)
    {
        if(!st[i])
        {
            path[u]=i;
            st[i]=true;
            dfs(u+1);
            st[i]=false;
        }
    }
}
int main(){
    cin >> n;
    dfs(0);
    return 0;
}

n-皇后问题题目链接

843. n-皇后问题 - AcWing题库

n-皇后问题题目类型

dps

n-皇后问题代码1

#include<iostream>

using namespace std;

const int N = 20;

int n;
char g[N][N];
bool col[N], dg[N], udg[N];
void dfs(int u)
{
    if(u==n)
    {
        for(int i=0;i<n;i++)  puts(g[i]);
        puts("");
        return ;
    }
    
    for(int i=0;i<n;i++)
    {
        if(!col[i] && !dg[u+i] && !udg[n-u+i])
        {
            g[u][i]='Q';
            col[i] = dg[u+i] = udg[n-u+i] = true;
            dfs(u+1);
            col[i] = dg[u+i] = udg[n-u+i] = false;
            g[u][i]='.';
        }
    }
}
int main(){
    cin >> n;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            g[i][j]='.';
        }
    }
    dfs(0);
    return 0;
}

n-皇后问题代码2

#include<iostream>

using namespace std;

const int N = 20;

int n;
char g[N][N];
bool row[N], col[N], dg[N], udg[N];
void dfs(int x, int y, int s)
{
    if(y==n) y=0, x++;
    if(x==n)
    {
        if(s==n)
        {
            for(int i=0;i<n;i++) puts(g[i]);
            puts("");
        }
        return ;
    }
    dfs(x, y+1, s);
    
    if(!row[x] && !col[y] && !dg[x+y] && !udg[x-y+n])
    {
        g[x][y]='Q';
        row[x]=col[y]=dg[x+y]=udg[x-y+n]=true;
        dfs(x,y+1,s+1);
        row[x]=col[y]=dg[x+y]=udg[x-y+n]=false;
        g[x][y]=' ';
    }
}
int main(){
    cin >> n;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            g[i][j]='.';
        }
    }
    dfs(0,0,0);
    return 0;
}

最讨厌你,也最喜欢你