n皇后问题(水)

#include<vector>
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef pair<int,int>pii;
pii p[10];
int v[10],sum,t,cnt;
int Abs(int a){
	return a>0?a:-a;
}
int judge(int st,int j){
	for(int i = 0;i<st;i++){
		if(Abs(p[i].first - st) == Abs(j - p[i].second)){
			return 0;
		}
	}return 1;
}
void dfs(int st){
	
	if(cnt == t ){
		sum ++;
		return;
	}else{
		if(st>=t){
			return ;
		}else{
			for(int i = 0;i<t;i++){
				if(!v[i] && judge(st,i)){
					p[st].first = st,p[st].second = i;
					cnt++;
					v[i] = 1;
					dfs(st+1);
					cnt--;
					v[i] = 0;
				}
			}
			dfs(st+1);
		}
	}
}
int main()
{
	cin>>t;
	sum = 0,cnt = 0;
	memset(v,0,sizeof(v));
	dfs(0);
	cout<<sum<<endl;
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/acer12138/article/details/80094570