题目:
The n-queens puzzle is the problem of placing nqueens 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皇后问题(两个皇后不能在同一行,不能在同一对角线),可是当时要求的是给出一个可行解,使用回溯法很容易得出。
而本题需要给出的是N皇后问题一共有多少个解。
解法:
我们使用三个标志位来记录 行,正对角线以及反对角线,当被占用时,打上标记,之后还使用DFS,使用回溯法进行求解。

正对角线,我们需要编号 2*n -1来进行标注
代码实现
class Solution {
int result = 0;
public int totalNQueens(int n) {
boolean[] visited = new boolean[n];
//2*n-1个斜对角线
boolean[] dia1 = new boolean[2*n-1];
boolean[] dia2 = new boolean[2*n-1];
fun(n,visited,dia1,dia2,0);
return result;
}
private void fun(int n,boolean[] visited,boolean[] dia1,boolean[] dia2,int rowIndex){
if(rowIndex == n){
result++;
return;
}
for(int i=0;i<n;i++){
//这一行、正对角线、反对角线都不能再放了,如果发现是true,停止本次循环
if(visited[i] || dia1[rowIndex+i] || dia2[rowIndex-i+n-1])
continue;
visited[i] = true;
dia1[rowIndex+i] = true;
dia2[rowIndex-i+n-1] = true;
fun(n,visited,dia1,dia2,rowIndex+1);
//reset 不影响回溯的下个目标
visited[i] = false;
dia1[rowIndex+i] = false;
dia2[rowIndex-i+n-1] = false;
}
}
}
本文探讨了N皇后问题的解决方案数量计算方法。通过使用回溯法和深度优先搜索(DFS),结合行、正对角线和反对角线的标记策略,有效地找出所有可行解的数量。

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



