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

LeetCode - N-Queens

2014-02-13 19:45 232 查看
N-Queens

2014.2.13 19:23

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.."]
]


Solution:

  The Eight Queens problem is a typical model for backtracking algorithm.

  For any pair of queens, their difference in x and y coordinates mustn't be 0 or equal, that's on the same row, column or diagonal line.

  The code is short and self-explanatory, please see for yourself.

  Total time complexity is O(n!). Space complexity is O(n!) as well, which comes from local parameters in recursive function calls.

Accepted code:

// 1CE, 1WA, 1AC, try to make the code shorter, it'll help you understand it better.
class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
a = nullptr;
res.clear();
if (n <= 0) {
return res;
}

a = new int
;
solveNQueensRecursive(0, a, n);
delete[] a;

return res;
}
private:
int *a;
vector<vector<string> > res;

void solveNQueensRecursive(int idx, int a[], const int &n) {
if (idx == n) {
// one solution is found
addSingleResult(a, n);
return;
}

int i, j;
// check if the current layout is valid.
for (i = 0; i < n; ++i) {
a[idx] = i;
for (j = 0; j < idx; ++j) {
if (a[j] == a[idx] || myabs(idx - j) == myabs(a[idx] - a[j])) {
break;
}
}
if (j == idx) {
// valid layout.
solveNQueensRecursive(idx + 1, a, n);
}
}
}

void addSingleResult(const int a[], int n) {
vector<string> single_res;
char *str = nullptr;

str = new char[n + 1];
int i, j;
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
str[j] = '.';
}
str[j] = 0;
str[a[i]] = 'Q';
single_res.push_back(string(str));
}

res.push_back(single_res);
single_res.clear();
delete []str;
}

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