一个很老的题了,在第一次写的时候超时,第二次写的时候想到了优化,结果还是超时=_=||,最后打表
但是我觉得这个优化很好,这样处理之后我觉得用位运算写八皇后就没问题了,当然N皇后类似
原理是任取一条左上到右下的直线,在这条直线上的点的横坐标和纵坐标之和相等,任取一条左下到右上的直线,
在这条直线上的横坐标和纵坐标之差相等,因此,只需要bool数组来标记相应的值即可
题目的边的范围是1~10,所以这儿写的是9+........
#include<cstdio>
#include<cstring>
using namespace std;
bool leftdown[30], upright[30], line[15];
int n, sum;
bool check(int row, int col);
void check_line(int rows);
int main(){
while (scanf("%d", &n) && n != 0) {
check_line(1);
printf("%d\n", sum);
sum = 0;
}
return 0;
}
void check_line(int rows){
for (int i = 1; i <= n;++i)
if (check(rows, i)){
if (rows == n)
sum++;
else{
leftdown[rows + i] = true, upright[9 + rows - i] = true;
line[i] = true;
check_line(rows + 1);
line[i] = false;
leftdown[rows + i] = false, upright[9 + rows - i] = false;
}
}
}
bool check(int row, int col){
return !line[col] && !upright[9 + row - col] && !leftdown[row + col];
}