原题网址:https://leetcode.com/problems/n-queens-ii/
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.

方法一:深度优先搜索,使用一维数组保存皇后位置。
public class Solution {
private int nQueens = 0;
private boolean isConflict(int[] rows, int row, int col) {
for(int i=0; i<row; i++) {
if (rows[i] == col) return true;
if (i-rows[i] == row-col) return true;
if (i+rows[i] == row+col) return true;
}
return false;
}
private void find(int[] queens, int step) {
if (step == queens.length) {
nQueens ++;
return;
}
for(int i=0; i<queens.length; i++) {
if (isConflict(queens, step, i)) continue;
queens[step] = i;
find(queens, step+1);
}
}
public int totalNQueens(int n) {
int[] queens = new int[n];
find(queens, 0);
return nQueens;
}
}
方法二:深度优先搜索,使用整数来保存皇后位置,使用位移处理行列、对角线的问题。
public class Solution {
private int total;
private void find(int step, int n, int col, int left, int right) {
if (step == n) {
total ++;
return;
}
int slot = col | left | right;
for(int i=0; i<n; i++) {
if (((slot >> i) & 1) != 0) continue;
int ncol = col | (1<<i);
int nleft = (left | (1<<i)) << 1;
int nright = (right | (1<<i)) >> 1;
find(step+1, n, ncol, nleft, nright);
}
}
public int totalNQueens(int n) {
find(0, n, 0, 0, 0);
return total;
}
}

本文介绍了LeetCode上的N皇后II问题的两种解决方案。一种是使用一维数组记录每个皇后的位置并通过递归进行深度优先搜索;另一种是利用位运算优化搜索过程,减少内存消耗并提高效率。
&spm=1001.2101.3001.5002&articleId=51468669&d=1&t=3&u=fe6cc02aff0d4e8ebfc7eb21cd8bd9a2)
375

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



