根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局。
样例
例1:
输入: n=1
输出: 1
解释:
1:
1
例2:
输入: n=4
输出: 2
解释:
1:
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
2:
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 0
解题思路:
和Lintcode 33. N皇后问题类似,更加简单,只需要用全局int变量存储即可。
public class Solution {
/**
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/
public int totalNQueens(int n) {
// write your code here
res = 0;
cols = new boolean[n];
dia1 = new boolean[2*n-1];
dia2 = new boolean[2*n-1];
dfs(n, new ArrayList<Integer>(), 0);
return res;
}
//cols[i]表示第i列被占用
boolean[] cols;
//dia1[i]表示第i右对角线被占用
boolean[] dia1;
//dia2[i]表示第i左对角线被占用
boolean[] dia2;
//结果
int res;
//list存入当前结果,其中下标表示横坐标,对应的值代表纵坐标
//index表示当前这一行
private void dfs(int n, List<Integer> list, int index){
if(list.size() == n){
res++;
return;
}
//对列进行遍历
for(int i=0; i<n; i++){
//如果当前列,左对角线和右对角线都没被占
if(!cols[i] && !dia1[index+i] && !dia2[index-i+n-1]){
cols[i] = true;
dia1[index+i] = true;
dia2[index-i+n-1] = true;
list.add(i);
dfs(n, list, index+1);
cols[i] = false;
dia1[index+i] = false;
dia2[index-i+n-1] = false;
list.remove(list.size()-1);
}
}
}
}

本文探讨了N皇后问题的简化版,旨在计算并返回所有可能的解决方案数量,而非具体的棋盘布局。通过深度优先搜索(DFS)算法,并利用布尔数组记录列、右对角线和左对角线的状态,有效地解决了问题。
3万+

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



