N皇后问题 II
题目
根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局。
样例
比如n=4,存在2种解决方案
题解
class Solution {
/**
* Calculate the total number of distinct N-Queen solutions.
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/
public int totalNQueens(int n) {
return getQueens(0,new int[n],n,0);
}
private int getQueens(int count,int[] row,int n,int index)
{
if (index == n)
{
return ++count;
}
for (int i=0; i<n;i++)
{
if (isValid(row,index,i))
{
row[index] = i;
count = getQueens(count,row,n,index+1);
row[index] = 0;
}
}
return count;
}
private boolean isValid(int[] row, int rowIndex, int columnIndex)
{
for (int i=0;i<rowIndex;i++)
{
if (row[i] == columnIndex || (Math.abs(row[i] - columnIndex) == Math.abs(i - rowIndex)) )
{
return false;
}
}
return true;
}
};
Last Update 2016.9.27