LeetCode52. N-Queens II
题目:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.

class Solution {
public:
int count = 0;
int totalNQueens(int n) {
std::vector<int> v(n, 0);
vector<vector<int>> map(n, v);
queen(map, 0);
return count;
}
bool check(vector<vector<int>> map, int col, int row) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < (int)map.size(); j++) {
if (map[i][j]) {
if (abs(i - row) == abs(j - col)) {
return false;
}
if (j == col)
return false;
}
}
}
return true;
}
void queen(vector<vector<int>> map, int row) {
for (size_t i = 0; i < map.size(); i++) {
if (check(map, i, row)) {
//count++;
map[row][i] = 1;
if (row == (int)(map.size() - 1)) {
map[row][i] = 0;
count++;
return;
}
queen(map, row+1);
map[row][i] = 0;
}
}
}
};
本文探讨了LeetCode上的N皇后II问题,介绍了一个通过回溯算法实现的C++解决方案,该方案计算出N皇后问题的所有不同解的数量,而不实际输出每种配置。
321

被折叠的 条评论
为什么被折叠?



