【两次过】Lintcode 34. N皇后问题 II

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

根据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);
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值