codevs1295 N皇后问题(经典中的经典,经典的不能再经典)

题目描述 Description

在n×n格的棋盘上放置彼此不受攻击的n个皇后。按照国际象棋的规则,皇后可以攻击与之处在同一行或同一列或同一斜线上的棋子。n后问题等价于再n×n的棋盘上放置n个皇后,任何2个皇后不妨在同一行或同一列或同一斜线上。

输入描述 Input Description

 给定棋盘的大小n (n ≤ 13)

输出描述 Output Description

 输出整数表示有多少种放置方法。

样例输入 Sample Input

8

样例输出 Sample Output

92

数据范围及提示 Data Size & Hint

n<=13

(时限提高了,不用打表了)

#include <iostream>
using namespace std;
int a[5][50],n,tot=0,c[50];
void search(int x){
	if(x==n)tot++;
	else for(int i=0;i<n;i++){
		if(!a[0][i] && !a[1][x+i] && !a[2][x-i+n]){
			c[x]=i;
			a[0][i]=a[1][x+i]=a[2][x-i+n]=1;
			search(x+1);
			a[0][i]=a[1][x+i]=a[2][x-i+n]=0;
		}
	}
}
int main(){
	cin>>n;
	search(0);
	cout<<tot<<endl;
	return 0;
}
原文地址:https://www.cnblogs.com/codetogether/p/7066589.html