# #33 N-Queens

79人阅读 评论(0)

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.

Example

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

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

Mycode（AC = 169ms）：

class Solution {
public:
/**
* Get all distinct N-Queen solutions
* @param n: The number of queens
* @return: All distinct solutions
* For example, A string '...Q' shows a queen on forth position
*/
vector<vector<string> > solveNQueens(int n) {
vector<vector<string>> ans;
if (n == 0) return ans;

vector<string> sofar;
unordered_set<int> col, diag;
solveNQueens(ans, sofar, n, col, diag);
return ans;
}

void solveNQueens(vector<vector<string>>& ans,
vector<string>& sofar,
int n,
unordered_set<int>& col,
unordered_set<int>& diag)
{
if (sofar.size() == n) {
ans.push_back(sofar);
return;
}

string tmp = nDots(n);
for (int i = 0; i < n; i++) {
// if there is no Q in same row, col, and diag,
// then tmp could be a potential ans
if (col.find(i) == col.end() &&
!findDiag(diag, sofar.size(), i, n))
{
col.insert(i);
diag.insert(sofar.size() * n + i);
tmp[i] = 'Q';
sofar.push_back(tmp);

solveNQueens(ans, sofar, n, col, diag);

sofar.pop_back();
tmp[i] = '.';
diag.erase(sofar.size() * n + i);
col.erase(i);
}
}
}

// write n '.' in a line
string nDots(int n) {
string str = "";
for (int i = 0; i < n; i++) {
str += ".";
}
return str;
}

// check whether there is Q in diag
bool findDiag(unordered_set<int>& diag, int i, int j, int n) {
for (auto it = diag.begin(); it != diag.end(); it++) {
int row = *it / n;
int col = *it % n;

if (abs(row - i) == abs(col - j)) return true;
}

return false;
}
};


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：12382次
• 积分：2244
• 等级：
• 排名：第16803名
• 原创：221篇
• 转载：1篇
• 译文：0篇
• 评论：10条
文章分类
文章存档
阅读排行
评论排行