用到了dfs算法
#include<iostream>
using namespace std;
int n;
int a[10][10] = { 0 };
int sum = 0;
void prin(int a[][10])
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
}
void dfs(int f)
{
if (f == n)
{
sum += 1;
// prin(a); // 打印解决方案,用于调试
return;
}
for (int i = 0; i < n; i++)
{
bool canPlace = true;
// 检查当前列
for (int j = 0; j < f; j++)
{
if (a[j][i] == 1)
{
canPlace = false;
break;
}
}
// 检查主对角线
for (int j = f - 1, k = i - 1; j >= 0 && k >= 0; j--, k--)
{
if (a[j][k] == 1)
{
canPlace = false;
break;
}
}
// 检查副对角线
for (int j = f - 1, k = i + 1; j >= 0 && k < n; j--, k++)
{
if (a[j][k] == 1)
{
canPlace = false;
break;
}
}
if (canPlace)
{
a[f][i] = 1;
dfs(f + 1);
a[f][i] = 0;
}
}
}
int main()
{
cin >> n;
dfs(0);
cout << sum;
return 0;
}
标签:10,canPlace,int,++,dfs,蓝桥,--,C++,皇后
From: https://blog.csdn.net/qq_52620232/article/details/137024767