# Meta / Amazon / Google / Microsoft Interview | Knight Probability in Chessboard Solution | LeetCode-688: Medium | JavaScript Implementation

*We will be seeing the solution to the LeetCode problem 93 in JavaScript. I hope you will find it useful.*

**Problem Statement:**

On an `n x n`

chessboard, a knight starts at the cell `(row, column)`

and attempts to make exactly `k`

moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`

, and the bottom-right cell is `(n - 1, n - 1)`

.

A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.

Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly k moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.

**Link to Problem**: https://leetcode.com/problems/knight-probability-in-chessboard/

# Implementation:

var knightProbability = function (n, k, row, column) {

let totalCount = Math.pow(8, k);

let totalSafeMoves = 0;

let memo = [];

let directions = [

[1, -2],

[1, 2],

[2, -1],

[2, 1],

[-2, 1],

[-2, -1],

[-1, 2],

[-1, -2],

];const isValid = (i, j) => {

if (i >= 0 && i < n && j >= 0 && j < n) {

return true;

} else {

return false;

}

};

const util = (i, j, possibleMoves) => {

if (!isValid(i, j)) {

return 0;

} else if (possibleMoves == k) {

return 1;

} else {

if (memo[i] && memo[i][j] != null && memo[i][j][possibleMoves]!=null) {

return memo[i][j][possibleMoves];

}

if (!memo[i]) {

memo[i] = [];

}

if(!memo[i][j]){

memo[i][j] = [];

}

memo[i][j][possibleMoves] = 0;

directions.forEach((delta) => {

let newX = i + delta[0];

let newY = j + delta[1];

memo[i][j][possibleMoves] = memo[i][j][possibleMoves] + util(newX, newY, possibleMoves + 1);

});

return memo[i][j][possibleMoves];

}

};

totalSafeMoves = util(row, column, 0);

return totalSafeMoves / totalCount;

}console.log(knightProbability(3, 3, 0, 0));

//Output: 0.06250

Thank you for reading hope this code is helpful to you.