-
Notifications
You must be signed in to change notification settings - Fork 0
/
knight-tour.js
97 lines (83 loc) · 2.47 KB
/
knight-tour.js
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
96
97
class KnightTour {
constructor(boardSize) {
this.boardSize = boardSize;
this.board = Array.from(Array(boardSize), () => Array(boardSize).fill(-1));
this.moves = [
[2, 1],
[1, 2],
[-1, 2],
[-2, 1],
[-2, -1],
[-1, -2],
[1, -2],
[2, -1]
];
}
isSafe(x, y) {
return x >= 0 && y >= 0 && x < this.boardSize && y < this.boardSize && this.board[x][y] === -1;
}
countPossibleMoves(x, y) {
let count = 0;
for (let move of this.moves) {
const newX = x + move[0];
const newY = y + move[1];
if (this.isSafe(newX, newY)) {
count++;
}
}
return count;
}
getAvailableMoves(x, y) {
const availableMoves = [];
for (let move of this.moves) {
const newX = x + move[0];
const newY = y + move[1];
if (this.isSafe(newX, newY)) {
availableMoves.push([newX, newY]);
}
}
return availableMoves;
}
knightTour() {
this.board[0][0] = 0; // Start from (0, 0)
// Begin with first move
if (!this.solveKnightTour(0, 0, 1)) {
console.log("No solution exists!");
return [];
}
return this.board;
}
solveKnightTour(x, y, moveCount) {
if (moveCount === this.boardSize * this.boardSize) {
return true; // All squares have been visited
}
const availableMoves = this.getAvailableMoves(x, y);
availableMoves.sort((a, b) => {
const countA = this.countPossibleMoves(a[0], a[1]);
const countB = this.countPossibleMoves(b[0], b[1]);
return countA - countB;
});
for (let move of availableMoves) {
const newX = move[0];
const newY = move[1];
this.board[newX][newY] = moveCount;
if (this.solveKnightTour(newX, newY, moveCount + 1)) {
return true;
}
// Backtrack
this.board[newX][newY] = -1;
}
return false;
}
}
const boardSize = 8; // 8x8 chessboard
const knightTour = new KnightTour(boardSize);
const solution = knightTour.knightTour();
console.log("Knight's Tour Solution:");
if (solution.length > 0) {
for (let row of solution) {
console.log(row);
}
} else {
console.log("No solution found!");
}