首页 技术 正文
技术 2022年11月8日
0 收藏 531 点赞 1,540 浏览 1110 个字

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

[leetcode]52. N-Queens II N皇后

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

题意:

code

 class Solution {
private int count; // 解的个数
// 这三个变量用于剪枝
private boolean[] columns; // 表示已经放置的皇后占据了哪些列
private boolean[] main_diag; // 占据了哪些主对角线
private boolean[] anti_diag; // 占据了哪些副对角线 public int totalNQueens(int n) {
this.count = 0;
this.columns = new boolean[n];
this.main_diag = new boolean[2 * n - 1];
this.anti_diag = new boolean[2 * n - 1]; int[] C = new int[n]; // C[i]表示第i行皇后所在的列编号
dfs(C, 0);
return this.count;
} void dfs(int[] C, int row) {
final int N = C.length;
if (row == N) { // 终止条件,也是收敛条件,意味着找到了一个可行解
++this.count;
return;
} for (int j = 0; j < N; ++j) { // 扩展状态,一列一列的试
final boolean ok = !columns[j] &&
!main_diag[row - j + N - 1] &&
!anti_diag[row + j];
if (!ok) continue; // 剪枝:如果合法,继续递归
// 执行扩展动作
C[row] = j;
columns[j] = main_diag[row - j + N - 1] =
anti_diag[row + j] = true;
dfs(C, row + 1);
// 撤销动作
// C[row] = -1;
columns[j] = main_diag[row - j + N - 1] =
anti_diag[row + j] = false;
}
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,023
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,513
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,360
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,143
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,774
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,852