nikunjsoni

688

Jun 12th, 2021
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     double knightProbability(int n, int k, int row, int column) {
  4.         vector<vector<double>> dp(n, vector<double>(n));
  5.         dp[row][column] = 1.0;
  6.         int dir[8][2] = {{2,1},{2,-1},{1,2},{1,-2},{-1,2},{-1,-2},{-2,1},{-2,-1}};
  7.        
  8.         for(; k>0; k--){
  9.             vector<vector<double>> dp1(n, vector<double>(n));
  10.             for(int r=0; r<n; r++){
  11.                 for(int c=0; c<n; c++){
  12.                     for(int d=0; d<8; d++){
  13.                         int nr = r+dir[d][0];
  14.                         int nc = c+dir[d][1];
  15.                         if(nr>=0 && nr<n && nc>=0 && nc<n){
  16.                             dp1[nr][nc] += (dp[r][c]/8.0);
  17.                         }
  18.                     }
  19.                 }
  20.             }
  21.             swap(dp1, dp);
  22.         }
  23.         double ans = 0.0;
  24.         for(int i=0; i<n; i++)
  25.             for(int j=0; j<n; j++)
  26.                 ans += dp[i][j];
  27.         return ans;
  28.     }
  29. };
Advertisement
Add Comment
Please, Sign In to add comment