Skip to content

Commit e3d58ff

Browse files
author
mic
committed
N皇后
1 parent 0a21a84 commit e3d58ff

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# Progress Every Day
22
## 传送门
3+
### [N皇后](https://github.com/chaoaiqi/study/blob/master/java/src/juejin/lc/leetCode/SolveNQueens.java)
34
### [基于AC自动机的敏感词匹配系统](https://github.com/chaoaiqi/study/blob/master/java/src/juejin/lc/tree/AhoCorasick.java)
45
### [统计字符串中某一单词出现的频率](https://github.com/chaoaiqi/study/blob/master/java/src/juejin/lc/tree/TrieTreeAlgo.java)
56
### [简易Trie树](https://github.com/chaoaiqi/study/blob/master/java/src/juejin/lc/tree/TrieTree.java)
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package juejin.lc.leetCode;
2+
3+
/**
4+
* N皇后
5+
*/
6+
public class SolveNQueens {
7+
/**
8+
* 皇后数组
9+
*/
10+
private int[] queens;
11+
/**
12+
* n皇后
13+
*/
14+
private int n;
15+
/**
16+
* 摆法数量
17+
*/
18+
private int count;
19+
20+
/**
21+
* 基于8皇后而衍生的N皇后
22+
*
23+
* @param n 皇后的数量
24+
*/
25+
private SolveNQueens(int n) {
26+
queens = new int[n];
27+
this.n = n;
28+
count = 0;
29+
}
30+
31+
/**
32+
* ]
33+
* 调用方式 calNQueens(0)从0开始遍历
34+
*
35+
* @param row 行
36+
*/
37+
private void calNQueens(int row) {
38+
if (row == n) {
39+
printQueens(queens);
40+
return;
41+
}
42+
for (int col = 0; col < n; col++) {
43+
if (isSatisfy(row, col)) {
44+
queens[row] = col;
45+
calNQueens(row + 1);
46+
}
47+
}
48+
}
49+
50+
/**
51+
* 遍历判断是否满足
52+
*
53+
* @param row 行
54+
* @param col 列
55+
* @return 返回值
56+
*/
57+
private boolean isSatisfy(int row, int col) {
58+
// System.out.println("(" + row + "," + col + ")");
59+
int leftUp = col - 1;
60+
int rightUp = col + 1;
61+
for (int i = row - 1; i >= 0; --i) {
62+
if (queens[i] == col) return false;
63+
if (leftUp >= 0 && queens[i] == leftUp) return false;
64+
if (rightUp < n && queens[i] == rightUp) return false;
65+
--leftUp;
66+
++rightUp;
67+
}
68+
return true;
69+
}
70+
71+
private void printQueens(int[] queens) {
72+
for (int row = 0; row < n; row++) {
73+
for (int col = 0; col < n; col++) {
74+
if (queens[row] == col) System.out.print("1 ");
75+
else System.out.print("0 ");
76+
}
77+
System.out.println();
78+
}
79+
System.out.println();
80+
++count;
81+
}
82+
83+
public static void main(String[] args) {
84+
int n = 8;
85+
SolveNQueens solveNQueens = new SolveNQueens(n);
86+
solveNQueens.calNQueens(0);
87+
System.out.println("共计" + solveNQueens.count + "种摆法.");
88+
}
89+
}

0 commit comments

Comments
 (0)