File tree Expand file tree Collapse file tree 2 files changed +90
-0
lines changed
java/src/juejin/lc/leetCode Expand file tree Collapse file tree 2 files changed +90
-0
lines changed Original file line number Diff line number Diff line change 1
1
# Progress Every Day
2
2
## 传送门
3
+ ### [ N皇后] ( https://github.com/chaoaiqi/study/blob/master/java/src/juejin/lc/leetCode/SolveNQueens.java )
3
4
### [ 基于AC自动机的敏感词匹配系统] ( https://github.com/chaoaiqi/study/blob/master/java/src/juejin/lc/tree/AhoCorasick.java )
4
5
### [ 统计字符串中某一单词出现的频率] ( https://github.com/chaoaiqi/study/blob/master/java/src/juejin/lc/tree/TrieTreeAlgo.java )
5
6
### [ 简易Trie树] ( https://github.com/chaoaiqi/study/blob/master/java/src/juejin/lc/tree/TrieTree.java )
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments