Skip to content

Commit e99b538

Browse files
committed
add an 8-queue solution
1 parent a642785 commit e99b538

File tree

4 files changed

+98
-1
lines changed

4 files changed

+98
-1
lines changed

Makefile

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,8 @@ PROGRAMS = m_based_demo \
6666
scc_demo \
6767
sort_demo \
6868
bubble_sort_demo \
69-
selection_sort_demo
69+
selection_sort_demo \
70+
8queue_demo
7071

7172
all: $(PROGRAMS)
7273

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@
8888
K-Means
8989
Knuth–Morris–Pratt algorithm
9090
Disjoint-Set
91+
8-Queue Problem
9192

9293
####贡献者 ( Contributors ) :
9394
Samana : for heavy work of MSVC compatability

include/8queen.h

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
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__

src/8queue_demo.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#include <stdio.h>
2+
#include <8queen.h>
3+
4+
int main(void) {
5+
alg::Queen8 q;
6+
q.solve();
7+
}
8+

0 commit comments

Comments
 (0)