题解 | #N皇后问题#
N皇后问题
https://www.nowcoder.com/practice/c76408782512486d91eea181107293b6
class Solution {
int a[10];
int count=0;
public:
/**
*
* @param n int整型 the n
* @return int整型
*/
int Nqueen(int n) {
cin >> n;
dfs(1,n);
return count;
}
bool queen(int i,int j){
if(i == 1)
return true;
int k = 1;
while(k < i){
if(j == a[k] || abs(k - i)==abs(a[k]-j)){
return false;
}
k++;
}
return true;
}
void dfs(int i,int n){
if(i == n+1){
count++;
return;
}
for(int j = 1; j <= n; j++){
if(queen(i,j) == true){
a[i] = j;
dfs(i+1,n);
}
}
}
};