Knight Probability - out of borad

ZeeshanAli-0704 - Aug 20 '22 - - Dev Community
const findProbablityOfKnight = (N, K, X, Y) => {
  const dir = [
    [1, 2],
    [2, 1],
    [-1, 2],
    [-2, 1],
    [-1, -2],
    [-2, -1],
    [1, -2],
    [2, -1],
  ];

  let memo = new Map();
  const stayOnBoard = (K, X, Y) => {
    if (X < 0 || Y < 0 || Y >= N || X >= N) {
      return 0;
    }
    if (K === 0) {
      return 1;
    }
    let key = `${K}:${X}:${Y}`;

    if (memo.has(key)) {
      return memo.get(key);
    }

    let probability = 0;

    for (let each of dir) {
      let [r, c] = each;
      probability += stayOnBoard(K - 1, X + r, Y + c) / 8;
    }
    memo.set(key, probability);
    return probability;
  };

  return stayOnBoard(K, X, Y);
};

console.log(findProbablityOfKnight(3, 2, 0, 0));

Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player