其他分享
首页 > 其他分享> > 【DFS】八皇后问题

【DFS】八皇后问题

作者:互联网

题目描述
8*8的棋盘上放置8个皇后,使它们互不攻击,即任意两个皇后不允许处在同一横排。同一纵列,也不允许处在同一与棋盘边框成45°角的斜线上。现在假设第一行的皇后的位置已经确定了,问符合条件的摆法有多少种?
输入
多组测试数据。先输入一个整数T表示组数。 然后是T组数据。每组数据一行,输入一个整数n( 1 <= n <= 8),表示第1行的皇后放的列数
输出
对于每组数据输出一行,值为满足条件摆法的种数。
样例输入 Copy

1
1

样例输出 Copy

4

经典DFS

AC 代码

#pragma GCC optimize(2)
#include<bits/stdc++.h>
#define abss(x) ((x)>(0)?(x):(-1)*(x))
#define maxs(a,b) ((a)>(b)?(a):(b))
#define mins(a,b) ((a)<(b)?(a):(b))
#define FOR(i,a,b) for(register int i=(a);i<=(b);i++)
#define ROF(i,a,b) for(register int i=(a);i>=(b);i--)
#define mem(a) memset(a,0,sizeof(a))
const int INF (1<<30);
const int inf (-1<<30);
using namespace std;

int matx[10][10];
int ans;

bool check_edge(int x,int y){
	if(x>=1 and x<=8 and y>=1 and y<=8)
		return true;
	return false;
}

bool check_unblocked(int x,int y){
	FOR(i,1,8){
		if(matx[i][y]==1)return false;
		if(matx[x][i]==1)return false;
	}
	int tx=x,ty=y;
	while(check_edge(tx,ty)) if(matx[tx++][ty++]==1)return false;
	tx=x,ty=y;
	while(check_edge(tx,ty)) if(matx[tx--][ty++]==1)return false;
	tx=x,ty=y;
	while(check_edge(tx,ty)) if(matx[tx++][ty--]==1)return false;
	tx=x,ty=y;
	while(check_edge(tx,ty)) if(matx[tx--][ty--]==1)return false;
	return true;
}

void dfs(int x,int y,int queen){
	if(x>queen)return;
	if(queen==8){
		ans++;
		return;
	}
	FOR(nx,x+1,8)
		FOR(ny,1,8){
			if(matx[nx][ny]==0 and check_unblocked(nx,ny)){
				matx[nx][ny]=1;
				dfs(nx,ny,queen+1);
				matx[nx][ny]=0;
			}
		}
}

int main(){
	int T;
	cin>>T;
	while(T--){
		int n;
		mem(matx);
		ans=0;
		cin>>n;
		matx[1][n]=1;
		dfs(1,n,1);
		cout<<ans<<endl;
	}
	return 0;
}

标签:return,tx,ty,int,matx,问题,--,DFS,皇后
来源: https://blog.csdn.net/qq_34010538/article/details/122639308