
Sponsored
Sponsored
In this approach, we utilize a 3D array `dp` where `dp[k][i][j]` represents the probability that the knight is on position `(i, j)` after making `k` moves. Initially, the knight is placed at `(row, column)`, so `dp[0][row][column] = 1`. For each move `k`, we calculate the probability of the knight being on each cell `(i, j)` by summing over probabilities of positions that can move to `(i, j)` in one knight move.
This involves iterating through each cell and updating the probabilities according to knight's possible moves.
Time Complexity: O(k * n^2), as each position on the board and each move is processed.
Space Complexity: O(k * n^2), for storing the DP states.
1public class KnightProbability {
2 public double knightProbability(int n, int k, int row, int column) {
3 double[][][] dp = new double[k + 1][n][n];
4 int[][] directions = {{2, 1}, {2, -1}, {-2, 1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};
5 dp[0][row][column] = 1.0;
6
7 for (int m = 1; m <= k; m++) {
8 for (int i = 0; i < n; i++) {
9 for (int j = 0; j < n; j++) {
10 for (int[] dir : directions) {
11 int ni = i + dir[0];
12 int nj = j + dir[1];
13 if (ni >= 0 && ni < n && nj >= 0 && nj < n) {
14 dp[m][ni][nj] += dp[m-1][i][j] / 8.0;
15 }
16 }
17 }
18 }
19 }
20
21 double result = 0.0;
22 for (int i = 0; i < n; i++) {
23 for (int j = 0; j < n; j++) {
24 result += dp[k][i][j];
25 }
26 }
27 return result;
28 }
29}Java implementation makes use of a 3D `dp` array to store probabilistic outcomes. Iterates over position and move arrays to determine potential winning positions using knight moves.
This approach leverages recursion along with memoization to optimize calculations. We define a recursive function to calculate the probability the knight remains within bounds after `k` moves. We utilize memoization to cache results of subproblems to avoid redundant calculations. If the knight's position ends within the board boundaries, it contributes to the final probability.
Time Complexity: O(k * n^2).
Space Complexity: O(k * n^2).
1
C implementation uses recursion with memoization to solve the problem. The `memo` table caches results for specific `(i, j, k)` states to avoid redundant computations.