#Leetcode# 52. N-Queens II
https://leetcode.com/problems/n-queens-ii/
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 the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4 Output: 2 Explanation: There are two distinct solutions to the 4-queens puzzle as shown below. [ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
题解:还是深搜 如果和之前的皇后不在同行列和对角线的时候可以放置
$n = 8$ 的时候有 $92$ 种放置方法
代码:
class Solution {
public:
int totalNQueens(int n) {
int ans = 0;
vector<int> pos(n, -1);
dfs(pos, 0, ans);
return ans;
}
void dfs(vector<int>& pos, int step, int &ans) {
int n = pos.size();
if(step == n) ans ++;
else {
for(int i = 0; i < n; i ++) {
if(ishere(pos, step, i)) {
pos[step] = i;
dfs(pos, step + 1, ans);
pos[step] = -1;
}
}
}
}
bool ishere(vector<int>& pos, int line, int row) {
for(int i = 0; i < line; i ++) {
if(row == pos[i] || abs(line - i) == abs(row - pos[i]))
return false;
}
return true;
}
};

浙公网安备 33010602011771号