您的位置:首页 > 产品设计 > UI/UE

[LeetCode] N-Queens II

2015-03-04 16:54 232 查看
Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.



思路:和 N-queens 一样,不过只统计个数而言,更加简单了

class Solution {
vector<int> x;
int m_res;

bool checkTwoPoints(int i, int j, int xi, int xj)
{
//cout << "check i\t" << i << endl;
//cout << "check j\t" << j << endl;
if(xi == xj) // same column
return false;
if( abs(xi-xj) == abs(i-j)) // diag
return false;
return true;
}

bool check(vector<int> x, int n) // check x
and x[0 .. n-1]
{
for(int i = 0; i < n; i++)
{
if(!checkTwoPoints(i, n, x[i], x
))
return false;
}
return true;
}

void dfs(int n)
{
if(n == x.size() )
{
//printVector(x);

m_res ++;
return;
}

for(int i = 0; i < x.size(); i++)
{
x
= i;

// check if x
is available
if(check(x, n))
dfs(n+1);
}

}
public:
int totalNQueens(int n)
{
x.resize(n);
m_res = 0;

dfs(0);
return m_res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: