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

LeetCode-N-Queens

2013-09-14 00:28 274 查看
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.."]
]
class Solution {
public:
int check(int* X,int k){
for(int i=0;i<k;i++){
if(X[i]==X[k]||abs(X[i]-X[k])==abs(i-k))return -1;
}
return 0;
}
vector<vector<string> > solveNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<string> > ret;
int* X=new int[n+1];
X[0]=-1;
int j=0;
while(j>=0)
{
X[j]++;
if(X[j]==n)
{
j--;
continue;
}
if(check(X,j)<0)
{
continue;
}
else
{
j++;
if(j==n){
vector<string> result;
for(int i=0;i<n;i++){
string s;
s.resize(n,'.');
s[X[i]]='Q';
result.push_back(s);
}
ret.push_back(result);
j--;
}
else
{
X[j]=-1;
}
}
}
delete X;
return ret;
}
};

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