当前位置:   article > 正文

【DFS】八皇后问题_经典的八皇后问题,即在一个8*8的棋盘上放8个皇后,使得这8个皇后无法互相攻击( 任

经典的八皇后问题,即在一个8*8的棋盘上放8个皇后,使得这8个皇后无法互相攻击( 任

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

1
1
  • 1
  • 2

样例输出 Copy

4
  • 1

经典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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/825513
推荐阅读
相关标签
  

闽ICP备14008679号