【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;
}
}