主要思路就是位运算,枚举每一行,然后当在某个(i,j)上放置之后将这一列和两个方向的对角线都标记上即可
class Solution {
public:
/**
*
* @param n int整型 the n
* @return int整型
*/
//diagonal1代表"/",diagonal2代表“\”
int dfs(int c, int diagonal1, int diagonal2, int r, int n){
int ans = 0;
if(r >= n){
return 1;
}
//枚举第r行的第i列
for(int i = 1; i <= n; ++i){
if(!(c & (1<<(i-1))) && !(diagonal1 & (1<<(i+r))) && !(diagonal2 & (1<<(n-i+r+1)))){
ans+=dfs(c | (1<<(i-1)), diagonal1 | (1<<(i+r)), diagonal2 | (1<<(n-i+r+1)), r+1, n);
}
}
return ans;
}
int Nqueen(int n) {
// write code here
return dfs(0, 0, 0, 0, n);
}
};