题解 | #N皇后问题#
N皇后问题
http://www.nowcoder.com/practice/c76408782512486d91eea181107293b6
难点:需要考虑皇后位置冲突的情况,使用‘位运算’记录不能放置皇后的位置,之后将穷举可以放置皇后的位置,当迭代到最后一行时,说明找到了一种放置皇后的方式
import java.util.*;
public class Solution {
/**
*
* @param n int整型 the n
* @return int整型
*/
int res = 0;
public int Nqueen (int n) {
// write code here
if(n<=0) return res;
// //初始化每一行皇后的位置
// int[] reme = new int[n];
// Arrays.fill(reme,-1);
dfs(0,0,0,0,n);
return res;
}
void dfs(int column,int bitst1,int bitst2,int cow,int n){
if(cow==n){
res++;
return;
}
//获得当期总共能够选择放置皇后的位置
int availableposition = ((1<<n)-1) & (~(column|bitst1|bitst2));
while(availableposition!=0){
//获取当前操作位置
int position = availableposition&(-availableposition);
//更新剩余的可选位置
availableposition &= (availableposition-1);
dfs(column|position,(bitst1|position)>>1,(bitst2|position)<<1,cow+1,n);
}
}
}