回溯算法(八皇后)

/*
  theme:八皇后
  回溯算法 
  coder:瞿鹏志 
  time:2015.1.11
 */
#include <iostream>
using namespace std;
#define N 15
#define M 8
class Eight_Queen{
   private:
	int left[N];
	int right[N];
	int colm[M];
	int cnt;
 	public:
 		Eight_Queen(){
 		int i;
 		cnt=0;
		 for(i=0;i<N;i++){
		 	left[i]=right[i]=0;
		 	if(i<M) colm[i]=-1;
		 }	
 		}
   void Queen(int i){
	for(int j=0;j<M;j++){
		if(left[i+j]!=1&&right[i-j+7]!=1&&colm[j]==-1){
			colm[j]=i;
			left[i+j]=right[i-j+7]=1;
			if(i==M-1){
			  cnt++; 	
			}else{
				Queen(i+1);
			}
		colm[j]=-1;
		left[i+j]=right[i-j+7]=0;
		}//end if 
	}//end for
   }
   int GetCnt(){
   	return cnt;
   }	
};
int main(void)
{
	Eight_Queen Queen1;
	Queen1.Queen(0);
	cout<<Queen1.GetCnt();
	return 0;
}

posted @ 2015-01-11 13:20  机智的程序员小熊  阅读(105)  评论(0编辑  收藏  举报