题目描述
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
代码
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int ans = 0;
int check(int arr[][10], int n,int x, int y)
{
for (int i = 0; i < n; i++)
{
if (arr[x][i] == 1 || arr[i][y] == 1)
return 0;
}
int x1 = x + 1;
int y1 = y + 1;
while (x1 >= 0 && x1 < 10 && y1 >= 0 && y1 < 10)
{
if (arr[x1][y1] == 1)
return 0;
x1++;
y1++;
}
int x2 = x - 1;
int y2 = y - 1;
while (x2 >= 0 && x2 < 10 && y2 >= 0 && y2 < 10)
{
if (arr[x2][y2] == 1)
return 0;
x2--;
y2--;
}
int x3 = x + 1;
int y3 = y - 1;
while (x3 >= 0 && x3 < 10 && y3 >= 0 && y3 < 10)
{
if (arr[x3][y3] == 1)
return 0;
x3++;
y3--;
}
int x4 = x - 1;
int y4 = y + 1;
while (x4 >= 0 && x4 < 10 && y4 >= 0 && y4 < 10)
{
if (arr[x4][y4] == 1)
return 0;
x4--;
y4++;
}
return 1;
}
void dfs(int arr[][10],int n, int x)
{
if (x == n)
{
ans++;
return;
}
for (int i = 0; i < n; i++)
{
if (check(arr,n,x,i)==1)
{
arr[x][i] = 1;
dfs(arr, n, x + 1);
arr[x][i] = 0;
}
}
}
int main()
{
int arr[10][10] = { 0 };
int n = 8;
dfs(arr, n, 0);
printf("%d\n", ans);
system("pause");
return 0;
}