
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.
1#include <vector>
2using namespace std;
3
4double knightProbability(int n, int k, int row, int column) {
5 vector<vector<vector<double>>> dp(k+1, vector<vector<double>>(n, vector<double>(n, 0.0)));
6 vector<pair<int, int>> directions{{2, 1}, {2, -1}, {-2, 1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};
7 dp[0][row][column] = 1.0;
8
9 for (int m = 1; m <= k; ++m) {
10 for (int i = 0; i < n; ++i) {
11 for (int j = 0; j < n; ++j) {
12 for (auto &dir : directions) {
13 int ni = i + dir.first;
14 int nj = j + dir.second;
15 if (ni >= 0 && ni < n && nj >= 0 && nj < n) {
16 dp[m][ni][nj] += dp[m-1][i][j] / 8.0;
17 }
18 }
19 }
20 }
21 }
22
23 double result = 0.0;
24 for (int i = 0; i < n; ++i) {
25 for (int j = 0; j < n; ++j) {
26 result += dp[k][i][j];
27 }
28 }
29 return result;
30}The solution follows the same logic as the C implementation. A 3D vector `dp` is used to track probabilities for each position on each move. Recognizes possible positions from the knight's possible moves to accumulate probability values.
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.