2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_52.java 2.14 KB
一键复制 编辑 原始数据 按行查看 历史
Charies Gavin 提交于 2020-02-06 12:44 . 初始化 myleetcode 项目
package com.hit.basmath.learn.recursion_ii;
import java.util.HashSet;
import java.util.Set;
/**
* 52. N-Queens II
* <p>
* The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
* <p>
* Given an integer n, return the number of distinct solutions to the n-queens puzzle.
* <p>
* Example:
* <p>
* Input: 4
* Output: 2
* <p>
* Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
* [
* [".Q..", // Solution 1
* "...Q",
* "Q...",
* "..Q."],
* <p>
* ["..Q.", // Solution 2
* "Q...",
* "...Q",
* ".Q.."]
* ]
*/
public class _52 {
/**
* don't need to actually place the queen,
* instead, for each row, try to place without violation on
* col/ diagonal1/ diagnol2.
* trick: to detect whether 2 positions sit on the same diagnol:
* if delta(col, row) equals, same diagnol1;
* if sum(col, row) equals, same diagnal2.
*/
private final Set<Integer> occupiedCols = new HashSet<Integer>();
private final Set<Integer> occupiedDiag1s = new HashSet<Integer>();
private final Set<Integer> occupiedDiag2s = new HashSet<Integer>();
public int totalNQueens(int n) {
return totalNQueensHelper(0, 0, n);
}
private int totalNQueensHelper(int row, int count, int n) {
for (int col = 0; col < n; col++) {
if (occupiedCols.contains(col))
continue;
int diag1 = row - col;
if (occupiedDiag1s.contains(diag1))
continue;
int diag2 = row + col;
if (occupiedDiag2s.contains(diag2))
continue;
// we can now place a queen here
if (row == n - 1)
count++;
else {
occupiedCols.add(col);
occupiedDiag1s.add(diag1);
occupiedDiag2s.add(diag2);
count = totalNQueensHelper(row + 1, count, n);
// recover
occupiedCols.remove(col);
occupiedDiag1s.remove(diag1);
occupiedDiag2s.remove(diag2);
}
}
return count;
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助