843. n-皇后问题 - AcWing题库
n皇后这道题目, 历来被作为理解深搜\回溯法的样板题, 首先我们可以用中规中矩的深搜来解决这道题:
#include<iostream>
using namespace std;
const int N=10;
int n;
char g[N][N];bool col[N],dg[N],udg[N];bool legal(int u,int i)
{return (!col[i]&&!dg[u+i]&&!udg[n-u+i]);
}void make_move(int u,int i)
{g[u][i]='Q';col[i]=dg[u+i]=udg[n-u+i]=true;
}void undo_move(int u,int i)
{g[u][i]='.';col[i]=dg[u+i]=udg[n-u+i]=false;
}void dfs(int u)
{if(u==n){for(int i=0;i<=n-1;i++) puts(g[i]);puts("");return ;}for(int i=0;i<=n-1;i++){if(legal(u,i)){make_move(u,i);dfs(u+1);undo_move(u,i);}}}int main()
{scanf("%d",&n);for(int i=0;i<=n-1;i++)for(int j=0;j<=n-1;j++) g[i][j]='.';dfs(0);return 0;
}