Advertisement
Notimecelduv

Chess Knight Tour

Jan 15th, 2022
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solveKnightTour() {
  2.   const length = 8;
  3.   const empty = -1;
  4.   // Any other structure for the offsets will slow the program down considerably.
  5.   const xOffsets = [2, 1, -1, -2, -2, -1, 1, 2];
  6.   const yOffsets = [1, 2, 2, 1, -1, -2, -2, -1];
  7.   const board = Array.from({ length }, _ => Array.from({ length }, __ => empty));
  8.   board[0][0] = 1;
  9.  
  10.   /**
  11.    * Determines whether `board[x][y]` can be filled in.
  12.    * @param {number} x A row index.
  13.    * @param {number} y A column index.
  14.    * @returns {boolean}
  15.    */
  16.   const isSafe = (x, y) => {
  17.     return x >= 0 && x < length && y >= 0 && y < length && board[x][y] === empty;
  18.   };
  19.  
  20.   /**
  21.    * Recursively fill in the board with increasing numbers representing a complete knight tour.
  22.    * @param {number} x The row index.
  23.    * @param {number} y the column index.
  24.    * @param {number} cnt The move index.
  25.    * @returns {boolean} Whether `x` and `y` eventually lead to a complete knight tour.
  26.    */
  27.   const solve = (x, y, cnt = 2) => {
  28.     if (cnt > length ** 2)
  29.       return true;
  30.  
  31.     for (let i = 0; i < length; i++) {
  32.       const nextX = x + xOffsets[i],
  33.         nextY = y + yOffsets[i];
  34.       if (!isSafe(nextX, nextY))
  35.         continue;
  36.  
  37.       board[nextX][nextY] = cnt;
  38.       if (solve(nextX, nextY, cnt + 1))
  39.         return true;
  40.  
  41.       board[nextX][nextY] = empty;
  42.     }
  43.  
  44.     return false;
  45.   };
  46.  
  47.   solve(0, 0);
  48.   console.log(
  49.     board.map(row => row
  50.       .map(n => String(n).padStart(2, "0"))
  51.       .join("—")
  52.     )
  53.   );
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement