My Knight Tour

 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
#include <iostream>
#define BSIZE 5
#define NMOVES 8
int move[NMOVES][2] = {
{1, 2},
{2, 1},
{2, -1},
{1, -2},
{-1, -2},
{-2, -1},
{-2, 1},
{-1, 2}
};
int board[BSIZE][BSIZE];
int count = 0;
bool checkEmptyAndInRang(int x, int y) {
if (x >= 0 && x < BSIZE
&& y >= 0 && y < BSIZE
&& -1 == board[x][y]) {
return true;
}
return false;
}
bool fillBoard(int x, int y) {
count++;
if (count == BSIZE*BSIZE) {
return true;
}
board[x][y] = count;
for (int i = 0; i < NMOVES; i++) {
int startX = x + move[i][0];
int startY = y + move[i][1];
if (checkEmptyAndInRang(startX, startY)) {
if(fillBoard(startX, startY)) {
return true;
}
}
}
return false;
}
void printBoard() {
// print board
int w, h;
for (h = 0; h < BSIZE; h++) {
for (w = 0; w < BSIZE; w++) {
if (w == 0) {
printf("%d\t", board[w][h]);
} else {
printf("\t%d\t", board[w][h]);
}
}
printf("\n\n");
}
}
int main() {
for (int i = 0; i < BSIZE; ++i) {
for (int j = 0; j < BSIZE; ++j) {
board[i][j] = -1;
}
}
int x = rand() % BSIZE;
int y = rand() % BSIZE;
fillBoard(x, y);
printBoard();
return 0;
}