My Knight Tour use Warnsdorff's algorithm

 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
88
89
90
91
92
93
94
95
#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];
bool checkEmptyAndInRang(int x, int y) {
if (x >= 0 && x < BSIZE
&& y >= 0 && y < BSIZE
&& -1 == board[x][y]) {
return true;
}
return false;
}
int getAccessilibity(int x, int y) {
int accessilibity = 0;
for (int i = 0; i < NMOVES; ++i) {
int nx = x + move[i][0];
int ny = y + move[i][1];
if (checkEmptyAndInRang(nx, ny)) {
accessilibity++;
}
}
return accessilibity;
}
int* getNextMove(int x, int y) {
int* smove = new int[2];
int access = NMOVES;
for (int i = 0; i < NMOVES; ++i) {
int nx = x + move[i][0];
int ny = y + move[i][1];
if (checkEmptyAndInRang(nx, ny) &&
getAccessilibity(nx, ny) <= access) {
access = getAccessilibity(nx, ny);
smove[0] = nx;
smove[1] = ny;
}
}
int* saved = smove;
delete [] smove;
return saved;
}
void fillBoard() {
int x = 0;// rand() % BSIZE;
int y = 0;// rand() % BSIZE;
int count = 0;
board[x][y] = count;
while (count != BSIZE*BSIZE) {
count++;
board[x][y] = count;
std::cout<<x<<"-"<<y<<": "<<board[x][y]<<"\n";
x = getNextMove(x, y)[0];
y = getNextMove(x, y)[1];
}
}
void printBoard() {
// print board
int w, h;
for (h = 0; h < BSIZE; ++h) {
for (w = 0; w < BSIZE; ++w) {
std::cout<<board[w][h]<<"\t";
}
std::cout<<std::endl;
}
}
int main() {
for (int i = 0; i < BSIZE; ++i) {
for (int j = 0; j < BSIZE; ++j) {
board[i][j] = -1;
}
}
fillBoard();
printBoard();
return 0;
}