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

Leetcode: N-Queens

2014-01-11 21:22 453 查看
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.."]
]

搞到很久,一个变量写错了,总是报Memory Limit Exceeded,郁闷。

class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
solveNQueensUtil(0, n);

return result;
}

void solveNQueensUtil(int step, int n) {
if (step == n) {
print(n);
return;
}

for (int i = 0; i < n; ++i) {
cols.push_back(i);
if (canPutQueen(step)) {
solveNQueensUtil(step + 1, n);
}
cols.pop_back();
}
}

bool canPutQueen(int step) {
for (int i = 0; i < step; ++i) {
if (cols[step] == cols[i] || abs(step - i) == abs(cols[step] - cols[i])) {
return false;
}
}

return true;
}

void print(int n) {
vector<string> solve;
for (int i = 0; i < n; ++i) {
string line;
for (int j = 0; j < n; ++j) {
line.push_back(cols[i] == j ? 'Q' : '.');
}
solve.push_back(line);
}
result.push_back(solve);
}

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