Another n-Queen Problem

n皇后问题:

Another n-Queen Problem

Description
I guess the n-queen problem is known by every person who has studied backtracking. In this problem you should count the number of placement of n queens on an n×n board so that no two queens attack each other. To make the problem a little bit harder (easier?), there are some bad squares where queens cannot be placed. Please keep in mind that bad squares cannot be used to block queens’ attack.
Even if two solutions become the same after some rotations and reflections, they are regarded as different. So there are exactly 92 solutions to the traditional 8-queen problem.
Input
The input consists of at most 10 test cases. Each case contains one integers n (3≤n≤15) in the first line. The following n lines represent the board, where empty squares are represented by dots ‘.’, bad squares are represented by asterisks ‘*’. The last case is followed by a single zero, which should not be processed.
Output
For each test case, print the case number and the number of solutions.
样例在代码最后面


八皇后模板:
tips:(y=kx+b k相同 判断b是否相同)
①同一正对角线上纵坐标和横坐标的差相同
②同一负对角线上纵坐标和横坐标的和相同
利用此性质可以将对角线上的状态使用一维数组存储=

OJ上要把数组开大一点,要不然WA


Code:

#include <bits/stdc++.h>
using namespace std;
const int N = 5e4 + 10;
int n,res;
char ch[55][55];
bool cc[55],dd[5][55];

void Q(int row) {
	if(row == n) {
		res++;
		return;
	}
	for(int i=0; i<n; i++) {
		if(!cc[i] && !dd[0][i+row] && !dd[1][n-1-i+row] && ch[row][i]=='.') {
			cc[i] = dd[0][i+row] = dd[1][n-1-i+row] = 1;
			Q(row + 1);
			cc[i] = dd[0][i+row] = dd[1][n-1-i+row] = 0;
		}
	}
}
int main() {
	int k=0;
	while(cin>>n && n) {
		res = 0;
		memset(cc,0,sizeof(cc));
		memset(dd,0,sizeof(dd));
		memset(ch,'\0',sizeof(ch));
		for(int i=0; i<n; i++) cin>>ch[i];
		Q(0);
		printf("Case %d: %d\n",++k,res);
	}
	return 0;
}
/*
Input
8
........
........
........
........
........
........
........
........
4
.*..
....
....
....
0
Output
Case 1: 92
Case 2: 1
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值