【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% 的用户