5
double dp[30][30][105];7
// x and y co-ordinates of 8 directions9
vector<int> dx = {-2, -2, -1, 1, 2, 2, 1, -1};11
vector<int> dy = {-1, 1, 2, 2, 1, -1, -2, -2};13
double dfs(int i, int j, int n, int moves) {14
// base case if we have reached out of grid16
if (i < 0 || i >= n || j < 0 || j >= n) return 0;18
// if no moves are remaining20
if (moves <= 0) return 1;22
// if already calculated24
if (dp[i][j][moves] != 0) return dp[i][j][moves];26
// find total possible ways of staying on chess board30
for (int k = 0; k < 8; k++) {31
int new_row = i + dx[k];33
int new_col = j + dy[k];35
ans += dfs(new_row, new_col, n, moves - 1);38
// for each cell there are 8 possible moves, so probablity will be no. of39
// successfull moves / 841
// store the result and return43
return dp[i][j][moves] = ans / 8.0;46
double knightProbability(int n, int k, int row, int column) {47
// initialize the dp with 049
memset(dp, 0, sizeof(dp));51
return dfs(row, column, n, k);