题解 | #八皇后#
八皇后
http://www.nowcoder.com/practice/fbf428ecb0574236a2a0295e1fa854cb
传一个指针进去捕捉终点
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <cstring>
using namespace std;
//个人思路:逐行地放皇后
int queen[8] = {
-1,-1,-1,-1,-1,-1,-1,-1
};
void DFS(int b, int row, int col, int* sum){
for(int i=0; i<8; i++){
if(i == row || queen[i] == -1){
continue;
}else if(queen[i]==col || abs(queen[i]-col)==abs(i-row)){
return;
}
}//通过这个考验,则本次放皇后是合法的
queen[row] = col;
if(row == 7){
(*sum)++;
if(*sum == b){
for(int i=0; i<8; i++){
printf("%d",queen[i]+1);
}
printf("\n");
}
}else{
for(int i=0; i<8; i++){
DFS(b, row+1, i, sum);
if(*sum == b){
return;
}
}
}
queen[row] = -1;
return;
}
int main(){
int b;
int sum = 0;
while(scanf("%d",&b) != EOF){
for(int i=0; i<8; i++){
DFS(b,0,i,&sum);
}
sum = 0;
memset(queen, -1, sizeof(queen));
}
return 0;
}