#include<stdio.h>
#define MAXQUEENS 20
#define MINQUEENS 4
enum BOOL{false, true};
typedef struct QueenData
{
int row;
int col;
}QueenData;
QueenData Queens[MAXQUEENS+1];
int nCount;
/********************************* Init **********************************/
int Init()
{
int Count=0;
printf("n皇后问题: 请输入皇后数(%d-%d):", MINQUEENS, MAXQUEENS);
scanf("%d", &Count);
if( Count<MINQUEENS || Count>MAXQUEENS)
return 0;
else
return Count;
}
/********************************* Check *************************************/
int Validate(int n, int row, int col)
{
int j, result=true;
for(j=1; j<n; j++)
{
if(j==row || Queens[j].row ==0) continue;
if(row == Queens[j].row || col == Queens[j].col) /* -- | */
return false;
if(Queens[j].row - row == Queens[j].col -col) /* / */
return false;
if(Queens[j].row-row == col-Queens[j].col ) /* / */
return false;
}
return result;
}
/********************************* SetQueen **********************************/
void SetQueen(int cur, int n)
{
int j;
Queens[cur].row=cur;
for(j=1; j<=n; j++)
{
Queens[cur].col=j;
if(Validate(n, cur,j)) /* pass */
{
if(cur==n)
nCount++;
else
SetQueen(cur+1, n);
}
}
Queens[cur].row=0;
Queens[cur].col=0;
}
/******************************* main ***************************************/
void main()
{
int n=Init();
if(!n) n=8;
SetQueen(1, n);
printf("/n%d 皇后问题的解法共有 %d 种/n", n, nCount);
}