#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int Queen;
//int *a;
short a[16];
int solution = 0;
int isSafe(int n, int i){
for (int m = 0; m < n; ++m)
{
if (a[m] == i || a[m] - i == n - m || a[m] - i == m - n)
{
return 0;
}//to check if current cordinate is valid
//if invalid, (x1 - x2)/(y1 - y2) == +1(-1)
}
return 1;
}
void place(int n){
for (short i = 0; i < Queen; ++i)
{
a[n] = i;
if (isSafe(n, i))
{
if (n == Queen - 1)
{
solution++;
}
else
{
place(n + 1);
}
}
}
}
int main(){
scanf("%d", &Queen);
double start = clock();
// a = (int *)malloc(Queen * sizeof(int));
place(0);
printf("解的个数为:%d\n", solution);
double end = clock();
// free(a);
printf("运行时间:%f\n", (end - start) / CLOCKS_PER_SEC);
return 0;
}
Q3: N皇后问题
最新推荐文章于 2024-10-12 00:23:45 发布