描述
N 皇后问题是指在 n * n 的棋盘上要摆 n 个皇后,
要求:任何两个皇后不同行,不同列也不在同一条斜线上,
求给一个整数 n ,返回 n 皇后的摆法数。
题解:首先要明白用数学标记正斜线(i-j)和反斜线(i+j),后利用hashset的特性,判断落子是否合理,利用递归依次判断全部的区域。
public class Solution {
/**
*
* @param n int整型 the n
* @return int整型
*/
int result=0;
Set<Integer> colum=new HashSet<>();
Set<Integer> posline=new HashSet<>();
Set<Integer> negline=new HashSet<>();
public int Nqueen (int n) {
// write code here
compute(0,n);
return result;
}
public void compute(int i,int n)
{
if(i==n){
result++;
return;
}
for(int j=0;j<n;j++)
{
if(colum.contains(j)||posline.contains(i-j)||negline.contains(i+j))
{
continue;
}
colum.add(j);
posline.add(i-j);
negline.add(i+j);
compute(i+1,n);
colum.remove(j);
posline.remove(i-j);
negline.remove(i+j);
}
}
}