【LeetCode】 52. N-Queens II N皇后 II(Hard)(JAVA)

【LeetCode】 52. N-Queens II N皇后 II(Hard)(JAVA)

题目地址: https://leetcode.com/problems/n-queens/

题目描述:

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.."]
]

题目大意

n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。

给定一个整数 n,返回 n 皇后不同的解决方案的数量。

解题方法

解法和上一题一模一样 【LeetCode】 51. N-Queens N皇后(Hard)(JAVA)

class Solution {
    int res = 0;
    public int totalNQueens(int n) {
        int[] col = new int[n];
        int[] rowPcol = new int[2 * n];
        int[] rowMcol = new int[2 * n];
        sH(0, col, rowPcol, rowMcol, n);
        return res;
    }

    public void sH(int index, int[] col, int[] rowPcol, int[] rowMcol, int n) {
        int row = index;
        if (row >= n) {
            res++;
            return;
        }
        for (int i = 0; i < n; i++) {
            if (col[i] > 0 || rowPcol[i + row] > 0 || rowMcol[row - i + n] > 0) continue;
            col[i] = 1;
            rowPcol[i + row] = 1;
            rowMcol[row - i + n] = 1;
            sH(index + 1, col, rowPcol, rowMcol, n);
            col[i] = 0;
            rowPcol[i + row] = 0;
            rowMcol[row - i + n] = 0;
        }
    }
}

执行用时 : 1 ms, 在所有 Java 提交中击败了 86.49% 的用户
内存消耗 : 36.5 MB, 在所有 Java 提交中击败了 5.09% 的用户

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值