n Queens Problem (Water)

#include<vector>
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef pair<int,int>pii;
pii p [10];
int v[10], I am, 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);
		}
	}
}
intmain()
{
	cin>>t;
	sum = 0,cnt = 0;
	memset(v,0,sizeof(v));
	dfs(0);
	cout<<sum<<endl;
	return 0;
 }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325999142&siteId=291194637
Recommended