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

leetcode---N-Queens II

2016-05-27 10:21 405 查看
Follow up for N-Queens problem.

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



class Solution {
public:
int ans = 0;

bool ok(int depth, int col, int n, vector<string> &tmp)
{
int sum = col + depth;
int c = 0;
for(int i=0; i<depth; i++)
{
c = depth - i;
if(tmp[i][col] == 'Q' || tmp[i][sum-i] == 'Q' || tmp[i][col-c] == 'Q')
return false;
}
return true;
}

void dfs(int depth, vector<string> &tmp, int n)
{
if(depth >= n)
{
ans++;
return;
}
for(int j=0; j<n; j++)
{
tmp[depth][j] = 'Q';
if(ok(depth, j, n, tmp))
dfs(depth+1, tmp, n);
tmp[depth][j] = '.';
}
}

int totalNQueens(int n)
{
vector<string> tmp;
for(int i=0; i<n; i++)
{
string s = "";
for(int j=0; j<n; j++)
s += '.';
tmp.push_back(s);
}
dfs(0, tmp, n);
return ans;

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