题目:https://www.luogu.org/problem/P1219
Description:
在n*n的棋盘上摆放棋子,要求棋子不能放在同一行同一列,也不能放在同一对角线上,同时不能放在与对角线平行的直线上,求有多少种放法。输出前三种。
对角线的横纵坐标相加减是一个定值。
Code:
#include<bits/stdc++.h>
using namespace std;
int a[50];//行
int b[50];//列
int c[50];//左下到右上对角线
int d[50];//左上到右下对角线
int n;
int cnt = 3;
int tim = 0;
void print()
{
if(cnt >= 1) //输出前三个结果
{
for(int i = 1; i <= n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
cnt--;
}
void dfs(int line)
{
if(line > n)
{
tim ++; //方案数+1
print();
return ;
}
for(int column = 1; column <= n; column++)
{
if(!b[column] && !c[line + column] && !d[line - column + n]) //+n,因为line - column 的结果可能为负数
{
a[line] = column;
b[column] = 1; //标记该列
c[line + column] = 1; //标记对角线
d[line - column + n] = 1;//标记对角线
dfs(line + 1);
b[column] = 0; //取消标记
c[line + column] = 0;
d[line - column + n] = 0;
}
}
}
int main()
{
cin >> n;
dfs(1);
cout << tim << endl; //总方案数
return 0;
}
本文介绍了一种解决N皇后问题的算法,通过使用回溯法在N*N的棋盘上放置棋子,确保棋子不位于同一行、列或对角线上。代码详细展示了如何标记和取消标记行列及对角线,以及如何递归地寻找所有可能的解决方案,并输出前三种布局。
3269

被折叠的 条评论
为什么被折叠?



