回溯法解n皇后问题

#include<bits/stdc++.h> 
using namespace std;
int n,sum;
int c[100];
void search(int cur){
	if(cur==n) sum++;
	else for(int i=0;i<n;i++)
	{
		bool ok=1;
		c[cur]=i;
		for(int j=0;j<cur;j++){
			if(c[cur]==c[j]||c[cur]-cur==c[j]-j||c[cur]+cur==c[j]+j){
				ok=0;
				break;
			}
		}
		if(ok) search(cur+1);
	}
} 
int main(){
	while(cin>>n){
		sum=0;
		search(0);
		cout<<sum<<endl; 
	}
	return 0;
}
posted @ 2018-08-15 20:42  ChunhaoMo  阅读(338)  评论(0)    收藏  举报