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
*/