File tree Expand file tree Collapse file tree 4 files changed +98
-1
lines changed Expand file tree Collapse file tree 4 files changed +98
-1
lines changed Original file line number Diff line number Diff line change @@ -66,7 +66,8 @@ PROGRAMS = m_based_demo \
66
66
scc_demo \
67
67
sort_demo \
68
68
bubble_sort_demo \
69
- selection_sort_demo
69
+ selection_sort_demo \
70
+ 8queue_demo
70
71
71
72
all : $(PROGRAMS )
72
73
Original file line number Diff line number Diff line change 88
88
K-Means
89
89
Knuth–Morris–Pratt algorithm
90
90
Disjoint-Set
91
+ 8-Queue Problem
91
92
92
93
####贡献者 ( Contributors ) :
93
94
Samana : for heavy work of MSVC compatability
Original file line number Diff line number Diff line change
1
+ /* ******************************************************************************
2
+ * DANIEL'1'S ALGORITHM IMPLEMENTAIONS
3
+ *
4
+ * /\ | _ _ ._ o _|_ |_ ._ _ _
5
+ * /--\ | (_| (_) | | |_ | | | | | _>
6
+ * _|
7
+ * 8-Queue
8
+ *
9
+ * http://en.wikipedia.org/wiki/Eight_queens_puzzle
10
+ ******************************************************************************/
11
+
12
+ #ifndef __8QUEEN_H__
13
+ #define __8QUEEN_H__
14
+
15
+ #include < stdio.h>
16
+ #include < string.h>
17
+
18
+ namespace alg {
19
+ class Queen8 {
20
+ private:
21
+ char board[8 ][8 ];
22
+ int cnt;
23
+ public:
24
+ void solve () {
25
+ memset (board, ' 0' , sizeof (board));
26
+ cnt = 0 ;
27
+ _solve (0 );
28
+ }
29
+ private:
30
+ void _solve (int row) { // start from 0
31
+ int i;
32
+ for (i=0 ;i<8 ;i++) {
33
+ board[row][i] = ' 1' ;
34
+ if (check (row, i)) {
35
+ if (row == 7 ) print ();
36
+ else _solve (row+1 );
37
+ }
38
+ board[row][i] = ' 0' ; // rollback
39
+ }
40
+ }
41
+
42
+ void print () {
43
+ printf (" chessboard: %d\n " ,++cnt);
44
+ int i,j;
45
+ for (i=0 ;i<8 ;i++) {
46
+ for (j=0 ;j<8 ;j++) {
47
+ printf (" %c " , board[i][j]);
48
+ }
49
+ printf (" \n " );
50
+ }
51
+ }
52
+
53
+ bool check (int row, int col) {
54
+ int i,j;
55
+
56
+ // cannot be same column
57
+ for (i=0 ;i<row;i++) {
58
+ if (board[i][col] == ' 1' ) {
59
+ return false ;
60
+ }
61
+ }
62
+
63
+ // cannot be diagnal
64
+ i = row-1 , j = col-1 ;
65
+ while (i>=0 && j >=0 ) {
66
+ if (board[i][j] == ' 1' ) {
67
+ return false ;
68
+ }
69
+ i--;
70
+ j--;
71
+ }
72
+
73
+ i = row-1 , j = col+1 ;
74
+ while (i>=0 && j <8 ) {
75
+ if (board[i][j] == ' 1' ) {
76
+ return false ;
77
+ }
78
+ i--;
79
+ j++;
80
+ }
81
+
82
+ return true ;
83
+ }
84
+ };
85
+ }
86
+
87
+ #endif // __8QUEEN_H__
Original file line number Diff line number Diff line change
1
+ #include < stdio.h>
2
+ #include < 8queen.h>
3
+
4
+ int main (void ) {
5
+ alg::Queen8 q;
6
+ q.solve ();
7
+ }
8
+
You can’t perform that action at this time.
0 commit comments