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

[LeetCode] N-Queens

2012-11-13 10:58 288 查看
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.



Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where
'Q'
and
'.'
both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
[".Q..",  // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.",  // Solution 2
"Q...",
"...Q",
".Q.."]
]

DFS to solve it!


class Solution {
private:
vector<vector<string> > ret;
int a[100];
bool canUse[100];
public:
bool check(int y, int n)
{
for(int i = 0; i < n; i++)
if (abs(i - n) == abs(y - a[i]))
return false;
return true;
}

void solve(int dep, int maxDep)
{
if (dep == maxDep)
{
vector<string> ans;
for(int i = 0; i < maxDep; i++)
{
string s;
for(int j = 0; j < a[i]; j++)
s += '.';
s += 'Q';
for(int j = 0; j < maxDep - (a[i] + 1); j++)
s += '.';
ans.push_back(s);
}
ret.push_back(ans);

return;
}

for(int i = 0; i < maxDep; i++)
if (canUse[i] && check(i, dep))
{
canUse[i] = false;
a[dep] = i;
solve(dep + 1, maxDep);
canUse[i] = true;
}
}

vector<vector<string> > solveNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ret.clear();
memset(canUse, true, sizeof(canUse));
solve(0, n);
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: