# N皇后 II

n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。

给你一个整数 n ,返回 n 皇后问题 不同的解决方案的数量。

 

示例 1:

输入:n = 4

输出:
2
解释:
如上图所示,4 皇后问题存在两个不同的解法。

示例 2:

输入:n = 1

输出:
1

 

提示:

  • 1 <= n <= 9
  • 皇后彼此不能相互攻击,也就是说:任何两个皇后都不能处于同一条横行、纵行或斜线上。

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; int n = 4; int res; res = sol.totalNQueens(n); cout << res; return 0; } ``` ## 答案 ```cpp class Solution { public: int totalNQueens(int n) { int res = 0; int queenPos[100]; NQueen(res, n, 0, queenPos); return res; } void NQueen(int &res, int N, int k, int queenPos[]) { int i; if (k == N) { res++; return; } for (i = 0; i < N; i++) { int j; for (j = 0; j < k; j++) { if (queenPos[j] == i || abs(queenPos[j] - i) == abs(k - j)) { break; } } if (j == k) { queenPos[k] = i; NQueen(res, N, k, queenPos); } } } }; ``` ## 选项 ### A ```cpp class Solution { public: int totalNQueens(int n) { vector stack(n); return dfs(n, 0, stack); } private: int dfs(int n, int row, vector &stack) { int count = 0; if (row == n) { return count + 1; } else { for (int i = 0; i < n; i++) { if (row == 0 || !conflict(stack, row, i)) { stack[row] = i; count += dfs(n, row + 1, stack); } } return count; } } bool conflict(vector &stack, int row, int col) { for (int i = 0; i < row; i++) { if (col == stack[i] || abs(row - i) == abs(col - stack[i])) { return true; } } return false; } }; ``` ### B ```cpp class Solution { public: void recurse(vector solution, int pos, vector> validPos, int &result) { int n = solution[0].size(); if (pos == n) { result++; return; } for (int i = 0; i < n; i++) { if (!validPos[pos][i]) continue; vector> newPos = validPos; for (int j = pos; j < n; j++) { newPos[j][i] = false; if (i - j + pos >= 0) newPos[j][i - j + pos] = false; if (i + j - pos < n) newPos[j][i + j - pos] = false; } solution[pos][i] = 'Q'; recurse(solution, pos + 1, newPos, result); solution[pos][i] = '.'; } return; } int totalNQueens(int n) { int result = 0; vector solution(n, string(n, '.')); vector> validPos = vector>(n, vector(n, true)); recurse(solution, 0, validPos, result); return result; } }; ``` ### C ```cpp class Solution { public: bool isvalid(vector &temp, int i, int j) { //判断棋盘是否有效 //for (int k = 0; k= 0 && q >= 0; --p, --q) { //判断左上对角线 if (temp[p][q] == 'Q') return false; } for (int p = i - 1, q = j + 1; p >= 0 && q < temp.size(); --p, ++q) { //判断右上对角线 if (temp[p][q] == 'Q') return false; } return true; } int dfs(int &count, vector &temp, int i, int n) { if (i == n) return ++count; for (int j = 0; j < n; ++j) { if (isvalid(temp, i, j)) { temp[i][j] = 'Q'; //递归前修改 dfs(count, temp, i + 1, n); } temp[i][j] = '.'; //递归后恢复 } return count; } int totalNQueens(int n) { int count = 0; string aa; for (int i = 0; i < n; ++i) aa += '.'; vector temp(n, aa); return dfs(count, temp, 0, n); } }; ```