【LeetCode】#52N皇后II(N-Queens II)

N皇后问题求解数量
本文探讨了N皇后问题,即如何将N个皇后放置在N×N的棋盘上,使得任意两个皇后都无法互相攻击。通过递归回溯算法,实现了一种有效的解决方案,用于计算所有可能的布局数量。

【LeetCode】#52N皇后II(N-Queens II)

题目描述

n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
给定一个整数 n,返回 n 皇后不同的解决方案的数量。

示例

输入: 4
输出: 2
解释: 4 皇后问题存在如下两个不同的解法。
[
[".Q…", // 解法 1
“…Q”,
“Q…”,
“…Q.”],

["…Q.", // 解法 2
“Q…”,
“…Q”,
“.Q…”]
]

Description

The n-queens puzzle is the problem of placing n queens 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…”]
]

解法

class Solution {
    private boolean col[];
    private boolean dia1[];
    private boolean dia2[];
    public int totalNQueens(int n) {
        col = new boolean[n];
        dia1 = new boolean[2*n-1];
        dia2 = new boolean[2*n-1];
        return putQueen(n, 0);
    }
    private int putQueen(int n, int index){
        int res = 0;
        if(index==n)
            return 1;
        for(int i=0; i<n; i++){
            if(!col[i] && !dia1[i-index+n-1] && !dia2[i+index]){
                col[i] = true;
                dia1[i-index+n-1] = true;
                dia2[i+index] = true;
                res += putQueen(n, index+1);
                col[i] = false;
                dia1[i-index+n-1] = false;
                dia2[i+index] = false;
            }
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值