Skip to content

Commit 474fce2

Browse files
author
wangpeng
committed
feat(HARD): add _52_totalNQueens
1 parent 10ea01b commit 474fce2

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package pp.arithmetic.leetcode;
2+
3+
/**
4+
* Created by wangpeng on 2019-05-31.
5+
* 52. N皇后 II
6+
* <p>
7+
* n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
8+
*
9+
* <image src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/8-queens.png"></image>
10+
* <p>
11+
* 上图为 8 皇后问题的一种解法。
12+
* <p>
13+
* 给定一个整数 n,返回 n 皇后不同的解决方案的数量。
14+
* <p>
15+
* 示例:
16+
* <p>
17+
* 输入: 4
18+
* 输出: 2
19+
* 解释: 4 皇后问题存在如下两个不同的解法。
20+
* [
21+
* [".Q..", // 解法 1
22+
* "...Q",
23+
* "Q...",
24+
* "..Q."],
25+
* <p>
26+
* ["..Q.", // 解法 2
27+
* "Q...",
28+
* "...Q",
29+
* ".Q.."]
30+
* ]
31+
*
32+
* @see <a href="https://leetcode-cn.com/problems/n-queens-ii/">n-queens-ii</a>
33+
*/
34+
public class _52_totalNQueens {
35+
public static void main(String[] args) {
36+
_52_totalNQueens totalNQueens = new _52_totalNQueens();
37+
System.out.println(totalNQueens.totalNQueens(5));
38+
}
39+
40+
//运算结果
41+
private int resultCount = 0;
42+
43+
/**
44+
* 解题思路(回溯算法):
45+
* 1.创建一个大小为n的数组,保存摆放皇后的位置
46+
* 2.从第一位开始尝试,一直取到N,每一次摆放皇后都得判断是否满足条件
47+
* 3.如摆放过程中发现没有满足条件的位置,则回溯上一位并寻找下一个可放置的位置
48+
* 4.如n个皇后都正确摆放,则结果+1,回溯上一位寻找下一个可放置的位置
49+
*
50+
* @param n
51+
* @return
52+
*/
53+
public int totalNQueens(int n) {
54+
int[] positions = new int[n];
55+
dfs(positions, 0, n);
56+
return resultCount;
57+
}
58+
59+
private void dfs(int[] positions, int index, int n) {
60+
if (index >= n) return;
61+
for (int i = 0; i < n; i++) {
62+
positions[index] = i;
63+
if (isMatch(positions, index)) {
64+
if (index == n - 1) {
65+
resultCount++;
66+
} else {
67+
dfs(positions, index + 1, n);
68+
}
69+
}
70+
}
71+
}
72+
73+
/**
74+
* 是否满足N皇后的规则,横、竖、斜边不能放
75+
*
76+
* @param positions
77+
* @param index
78+
* @return
79+
*/
80+
private boolean isMatch(int[] positions, int index) {
81+
for (int i = 0; i < index; i++) {
82+
//判断横向和斜向是否在一条线上即可,因为竖向用一位数组存储就避免了
83+
if (positions[i] == positions[index] || Math.abs(positions[i] - positions[index]) == index - i) {
84+
return false;
85+
}
86+
}
87+
return true;
88+
}
89+
90+
}

0 commit comments

Comments
 (0)