会下国际象棋的人都很清楚:皇后可以在横、竖、斜线上不限步数地吃掉其他棋子。如何将8个皇后放在棋盘上(有8 * 8个方格),使它们谁也不能被吃掉!这就是著名的八皇后问题。
输入
一个整数n( 1 < = n < = 10 )
输出
每行输出对应一种方案,按字典序输出所有方案。每种方案顺序输出皇后所在的列号,相邻两数之间用空格隔开。如果一组可行方案都没有,输出“no solute!”
具体思路:
初始化一个canIDrop的bool类型三维数组,canIDrop[1][2][3] == true表示:选择第一行的落棋位置后第二行第三列是允许我落棋的,第n次落棋要更新canIDrop[n+1]指向的二维数组(ban()函数),从第n次DFS递归返回时将canIDrop恢复成原样(unban()函数),第n步落棋通过canIDrop[n][x][y]判断(x,y)这个位置可不可以落棋。
#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
const int maxN = 11;
int n;
int ans_num;
vector<int> ans;
bool canIDrop[maxN][maxN][maxN];
void ban(int x , int y , int step){//将落点的行、列、斜线全部ban掉
for(int i = 1;i <= n;i++){
for(int j = 1;j <= n;j++){
canIDrop[step][i][j] = canIDrop[step-1][i][j];
}
}
//复制上一步所ban掉的位置
for(int i = 1 ; i <= n;i++){
canIDrop[step][x][i] = false;
canIDrop[step][i][y] = false;
}
//ban掉该点所在的行与列
int i = x,j = y;
while(i > 0 && j > 0){//左上
canIDrop[step][i--][j--] = false;
}
i = x;
j = y;
while(i <= n && j <= n){//右下
canIDrop[step][i++][j++] = false;
}
i = x;
j = y;
while(i > 0 && j <= n){//右上
canIDrop[step][i--][j++] = false;
}
i = x;
j = y;
while(i <= n && j > 0){//左下
canIDrop[step][i++][j--] = false;
}
}
void unban(int step){
for(int i = 1;i <= n;i++){
for(int j = 1;j <= n;j++){
canIDrop[step][i][j] = true;
}
}
//将这一层的canIdrop恢复
}
void DFS(int step){
if(step == n){
ans_num ++;//如果ans_num为0代表没有答案,作为最后输出nosolute的判断条件
for(int i = 0;i < n;i++){
printf("%d",ans[i]);
if(i != n-1){
printf(" ");
}else{
printf("\n");
}
}
}
for(int i = 1;i <= n;i++){
if(canIDrop[step][step+1][i]) {
ans.push_back(i);
ban(step + 1, i, step + 1);
DFS(step + 1);
ans.pop_back();
unban(step+1);
}
}
}
int main(){
while(scanf("%d",&n) != EOF) {
ans_num = 0;
memset(canIDrop , true , sizeof(bool)*maxN*maxN*maxN);//初始化canIdrop
DFS(0);
if(ans_num == 0){
printf("no solute!\n");
}
}
return 0;
}