Blue Bridge training - Reviewing the Old Queens 2n

Report problem solving: first put the Black Queen recapture the White Queen.

#include<iostream>
using namespace std;
const	int N=22;
int col[N],col2[N];
int a[N][N];
int n;
int ans;
bool check(int t,int u)
{
	for(int i=0;i<u;i++)
	if(col[i]==t||abs(t-col[i])==abs(i-u))	return false;
	return true;
}
bool check2(int t, int u)
{
	for(int i=0;i<u;i++)
	if(col2[i]==t||abs(t-col2[i])==abs(i-u))	return false;
	return true;
}
void dfs2(int u)
{
	if(u==n)
	{
		ans++;
		return ;
	}
	for(int i=0;i<n;i++)
	{
		if(check2(i,u)&&a[u][i]==1)
		{
			col2[u]=i;
			dfs2(u+1);
		}
	}
}
void dfs(int u)
{
	if(u==n)
	{
		dfs2(0);
		return ;
	}
	for(int i=0;i<n;i++)
	{
		if(check(i,u)&&a[u][i]==1)
		{	
		col[u]=i;
		a[u][i]=2;
		dfs(u+1);
		a[u][i]=1;
		}
	}
}
int main()
{
	cin>>n;
	for(int i=0;i<n;i++)
	for(int j=0;j<n;j++)
	cin>>a[i][j];
	dfs(0);
	cout<<ans<<endl;
}
Published 165 original articles · won praise 8 · views 2480

Guess you like

Origin blog.csdn.net/qq_45961321/article/details/104955376