# C语言 之 n皇后问题

/*

author:  yanghongchao

time: 2018/4/17

*/

#include <stdio.h>

#define MAX_NUMBER 100

int main()
{
int number_of_queen(int a[], int n, int k, int j, int count);
int n;
int m;
scanf("%d", &n);
int a[MAX_NUMBER] = {-1};
m = number_of_queen(a, n, 0, 0, 0);
printf("the n latitice have maximal %d queen.\n", m);
return 0;
}

int number_of_queen(int a[], int n, int k, int j, int count) //a[n] 为 n元数组第i个位置的元素k表示第i行的第k列放kueen，
{
if (k == 0 && j >= n)
{
return count;
}
if (k == n)
{
int x;
for (x=0; x<n; x++) printf("%d ", a[x]);
printf("\n");
count++;
j = a[k-1] + 1; a[k-1] = -1;
number_of_queen(a, n, k-1, j, count);
}
else
{
int i = 0;
int b[100] = {0};
for (i = 0; i < k; i++){      // 建立一个列表来确定在当前的行，第k行不能填数字的位置标记为1
b[a[i]] = 1;
if (0 <= a[i] + k - i && a[i] + k - i < n)
b[a[i]+k-i] = 1;
if (0 <= a[i] + i - k && a[i] + i -k < n)
b[a[i]+i-k] = 1;
}
while (b[j] != 0)
j++;                      //    由数字j开始搜索第一个能填入的数字
if (j >= n){
j = a[k-1] + 1; a[k-1] = -1;
number_of_queen(a, n, k-1, j, count);
}
else if (j < n && k < n){
a[k] = j;
number_of_queen(a, n, k + 1, 0, count);
}
}

}