AcWing 1432. 棋盘挑战
原题链接
中等
作者:
Winkel
,
2021-02-06 22:32:46
,
所有人可见
,
阅读 309
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 15;
int n, res;
bool col[N], dg[2*N], udg[2*N];
int path[N];
void dfs(int x) //行
{
if(x > n)
{
res++;
if(res <= 3)
{
for(int i = 1; i <= n; i++) cout << path[i] << ' ';
cout << endl;
}
return;
}
for(int y = 1; y <= n; y++) //枚举列
{
if(!col[y] && !dg[x+y] && !udg[x-y+n])
{
path[x] = y; //找到在行x上可以放的列的位置
col[y] = dg[x+y] = udg[x-y+n] = true; //标记已搜索
dfs(x + 1);
path[x] = 0;
col[y] = dg[x+y] = udg[x-y+n] = false; //恢复成未搜索状态
}
}
}
int main()
{
cin >> n;
dfs(1); //第一行开始搜索
cout << res;
return 0;
}