-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy path8queen.h
87 lines (77 loc) · 1.58 KB
/
8queen.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*******************************************************************************
* DANIEL'1'S ALGORITHM IMPLEMENTAIONS
*
* /\ | _ _ ._ o _|_ |_ ._ _ _
* /--\ | (_| (_) | | |_ | | | | | _>
* _|
* 8-Queue
*
* http://en.wikipedia.org/wiki/Eight_queens_puzzle
******************************************************************************/
#ifndef ALGO_8QUEEN_H__
#define ALGO_8QUEEN_H__
#include <stdio.h>
#include <string.h>
namespace alg {
class Queen8 {
private:
char board[8][8];
int cnt;
public:
void solve() {
memset(board, '0', sizeof(board));
cnt = 0;
_solve(0);
}
private:
void _solve(int row) { // start from 0
int i;
for (i=0;i<8;i++) {
board[row][i] = '1';
if (check(row, i)) {
if (row == 7) print();
else _solve(row+1);
}
board[row][i] = '0'; // rollback
}
}
void print() {
printf("chessboard: %d\n",++cnt);
int i,j;
for (i=0;i<8;i++) {
for (j=0;j<8;j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
bool check(int row, int col) {
int i,j;
// cannot be same column
for (i=0;i<row;i++) {
if (board[i][col] == '1') {
return false;
}
}
// cannot be diagnal
i = row-1, j = col-1;
while (i>=0 && j >=0) {
if (board[i][j] == '1') {
return false;
}
i--;
j--;
}
i = row-1, j = col+1;
while (i>=0 && j <8) {
if (board[i][j] == '1') {
return false;
}
i--;
j++;
}
return true;
}
};
}
#endif //ALGO_8QUEEN_H__