MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / OpenKnightTour

Class OpenKnightTour

Backtracking/KnightTour.js:3–70  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1// Wikipedia: https://en.wikipedia.org/wiki/Knight%27s_tour
2
3class OpenKnightTour {
4 constructor(size) {
5 // Constructor to initialize the chessboard and size
6 this.board = new Array(size).fill(0).map(() => new Array(size).fill(0))
7 this.size = size
8 }
9
10 getMoves([i, j]) {
11 // Helper function to get the valid moves of the knight from the current position
12 const moves = [
13 [i + 2, j - 1],
14 [i + 2, j + 1],
15 [i - 2, j - 1],
16 [i - 2, j + 1],
17 [i + 1, j - 2],
18 [i + 1, j + 2],
19 [i - 1, j - 2],
20 [i - 1, j + 2]
21 ]
22
23 // Filter out moves that are within the board boundaries
24 return moves.filter(
25 ([y, x]) => y >= 0 && y < this.size && x >= 0 && x < this.size
26 )
27 }
28
29 isComplete() {
30 // Helper function to check if the board is complete
31 return !this.board.map((row) => row.includes(0)).includes(true)
32 }
33
34 solve() {
35 // Function to find the solution for the given board
36 for (let i = 0; i < this.size; i++) {
37 for (let j = 0; j < this.size; j++) {
38 if (this.solveHelper([i, j], 0)) return true
39 }
40 }
41 return false
42 }
43
44 solveHelper([i, j], curr) {
45 // Helper function for the main computation
46 if (this.isComplete()) return true
47
48 // Iterate through possible moves and attempt to fill the board
49 for (const [y, x] of this.getMoves([i, j])) {
50 if (this.board[y][x] === 0) {
51 this.board[y][x] = curr + 1
52 if (this.solveHelper([y, x], curr + 1)) return true
53 // Backtracking: If the solution is not found, reset the cell to 0
54 this.board[y][x] = 0
55 }
56 }
57 return false
58 }
59
60 printBoard(output = (value) => console.log(value)) {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected