首页 > 代码库 > 八皇后算法

八皇后算法

#include<iostream>   using namespace std;  #define MAX 8int queen[MAX]={0};int sum = 0;void show(){	printf("(");	for(int i =0;i<MAX;i++)	{		printf(" %d",queen[i]);	}	printf(")\n");	sum++;}int place(int n){	for(int i=0;i<n;i++)	{		if(queen[i] == queen[n] || abs(queen[i] -queen[n]) == (n-i))			return -1;	}	return 0;}void nqueen(int n){	for (int i =0;i<MAX;i++)	{		queen[n] = i;		if(!place(n))		{			if(n == MAX -1)				show();			else				nqueen(n+1);		}	}}int main(char**,int){	nqueen(0);    printf("%d",sum);	getchar();	return 0;}

 

八皇后算法