Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solveKnightTour() {
- const length = 8;
- const empty = -1;
- // Any other structure for the offsets will slow the program down considerably.
- const xOffsets = [2, 1, -1, -2, -2, -1, 1, 2];
- const yOffsets = [1, 2, 2, 1, -1, -2, -2, -1];
- const board = Array.from({ length }, _ => Array.from({ length }, __ => empty));
- board[0][0] = 1;
- /**
- * Determines whether `board[x][y]` can be filled in.
- * @param {number} x A row index.
- * @param {number} y A column index.
- * @returns {boolean}
- */
- const isSafe = (x, y) => {
- return x >= 0 && x < length && y >= 0 && y < length && board[x][y] === empty;
- };
- /**
- * Recursively fill in the board with increasing numbers representing a complete knight tour.
- * @param {number} x The row index.
- * @param {number} y the column index.
- * @param {number} cnt The move index.
- * @returns {boolean} Whether `x` and `y` eventually lead to a complete knight tour.
- */
- const solve = (x, y, cnt = 2) => {
- if (cnt > length ** 2)
- return true;
- for (let i = 0; i < length; i++) {
- const nextX = x + xOffsets[i],
- nextY = y + yOffsets[i];
- if (!isSafe(nextX, nextY))
- continue;
- board[nextX][nextY] = cnt;
- if (solve(nextX, nextY, cnt + 1))
- return true;
- board[nextX][nextY] = empty;
- }
- return false;
- };
- solve(0, 0);
- console.log(
- board.map(row => row
- .map(n => String(n).padStart(2, "0"))
- .join("—")
- )
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement