题目内容
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
题目分析
n皇后问题,找出所有的可行解。通过本方法,没有记录皇后的坐标
代码
public class Solution {
private final Set<Integer> occupiedCols = new HashSet<Integer>();
private final Set<Integer> occupiedDiag1s = new HashSet<Integer>();
private final Set<Integer> occupiedDiag2s = new HashSet<Integer>();
public int totalNQueens(int n) {
return totalNQueensHelper(0, 0, n);
}
private int totalNQueensHelper(int row, int count, int n) {
for (int col = 0; col < n; col++) {
if (occupiedCols.contains(col))
continue;
int diag1 = row - col;
if (occupiedDiag1s.contains(diag1))
continue;
int diag2 = row + col;
if (occupiedDiag2s.contains(diag2))
continue;
// we can now place a queen here
if (row == n-1)
count++;
else {
occupiedCols.add(col);
occupiedDiag1s.add(diag1);
occupiedDiag2s.add(diag2);
count = totalNQueensHelper(row+1, count, n);
// recover
occupiedCols.remove(col);
occupiedDiag1s.remove(diag1);
occupiedDiag2s.remove(diag2);
}
}
return count;
}
}
本文介绍了一种解决N皇后问题的方法,该方法不输出具体的棋盘配置,而是返回所有不同解决方案的数量。通过使用三个集合来跟踪已占据的位置,递归地尝试放置皇后并计算可行解的数量。

1327

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



