Probability of Knight | Practice | GeeksforGeeks

Given an NxN chessboard and a Knight at position (x, y). The Knight has to take exactly K steps, where at each step it chooses any of the 8 directions uniformly at random. Find the probability that the Knight remains in the chessboard after taking K steps, with the condition that it cant enter the board again once it leaves it.
 
Example 1:
Input : N = 8, x = 0, y = 0, K = 3
Output: 0.125000

Example 2:
Input: N = 4, x = 1, y = 2, k = 4
Output: 0.024414

 
Your Task: 
You don't need to read or print anything. Your task is to complete the function findProb() which takes N, x, y and K as input parameter and returns the probability.
 
Expected Time Complexity : O(N 3)
Expected Space Complexity: O(N3)
 
Constraints:
1 <= N <= 100
0 <= x, y <= N
0 <= K <= N
+2
pritamkr2123 days ago
ALL FOUR SOLUTION -→RECURSIVE, MEMOZAITION,TABULATION, SPACE OPTIMAZTION (THANKS STRIVER FOR BEST DP PLAYLIST)
 1→ RECURSIVE=>
class Solution
{
    static boolean isSafe(int x,int y,int N){
        if(x>=0 && x<N && y>=0 && y<N)return true;
        return false;
    }
    private static double solver(int x,int y,int step,int N){
        double count=0;
        if(isSafe(x,y,N)){
            if(step==0)return 1;
            count+= solver(x-2, y+1, step-1,N);
            count+= solver(x-2, y-1, step-1,N);
            count+= solver(x-1, y+2, step-1,N);
            count+= solver(x-1, y-2, step-1,N);
            count+= solver(x+1, y+2, step-1,N);
            count+= solver(x+1, y-2, step-1,N);
            count+= solver(x+2, y+1, step-1,N);
            count+= solver(x+2, y-1, step-1,N);
        }
        return count;
    }
    
    public double findProb(int N, int start_x, int start_y, int step)
    {
       // recursion solution
       
       double count =solver(start_x,start_y,step,N);
       return count/Math.pow(8,step);
       
    }
}
 
 2-→ MEMOZATION =>
 
class Solution
{
    static Double[][][]dp;
    static boolean isSafe(int x,int y,int N){
        if(x>=0 && x<N && y>=0 && y<N)return true;
        return false;
    }
    private static double solver(int x,int y,int step,int N){
        double count=0;
        if(isSafe(x,y,N)){
            if(step==0)return 1;
            if(dp[x][y][step]!=null)return dp[x][y][step];
            count+= solver(x-2, y+1, step-1,N);
            count+= solver(x-2, y-1, step-1,N);
            count+= solver(x-1, y+2, step-1,N);
            count+= solver(x-1, y-2, step-1,N);
            count+= solver(x+1, y+2, step-1,N);
            count+= solver(x+1, y-2, step-1,N);
            count+= solver(x+2, y+1, step-1,N);
            count+= solver(x+2, y-1, step-1,N);
            dp[x][y][step]=count;
        }
        return count;
    }
    
    public double findProb(int N, int start_x, int start_y, int step)
    {
       // memoziation solution
       dp=new Double[N][N][step+1];
       double count =solver(start_x,start_y,step,N);
       return count/Math.pow(8,step);
       
    }
}
 3-→ TABULATION=>
 

class Solution
{
    static boolean isSafe(int x,int y,int N){
        if(x>=0 && x<N && y>=0 && y<N)return true;
        return false;
    }
    
    int[][] dirs = {{2, 1}, {-2, 1}, {2, -1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};
    
    public double findProb(int n, int start_x, int start_y, int step)
    {
       // Tabulation solution
       double[][][] dp=new double[step+1][n][n];
       dp[0][start_x][start_y]=1;
       for(int k=1;k<=step;k++){
           for(int i=0;i<n;i++){
               for(int j=0;j<n;j++){
                   for(int[]dir:dirs){
                       int x=i+dir[0];
                       int y=j+dir[1];
                       if(isSafe(x,y,n)){
                           dp[k][i][j]+=dp[k-1][x][y]/8.0;
                       }
                   }
               }
           }
       }
       
       double res=0;
       for(int i=0;i<n;i++){
           for(int j=0;j<n;j++){
               res+=dp[step][i][j];
           }
       }
       return res;
       
    }
}
 
 4-→ SPACE OPTIMAZATION=>
 

class Solution
{
    static boolean isSafe(int x,int y,int N){
        if(x>=0 && x<N && y>=0 && y<N)return true;
        return false;
    }
    
    int[][] dirs = {{2, 1}, {-2, 1}, {2, -1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};
    
    public double findProb(int n, int start_x, int start_y, int step)
    {
       // space optimization solution
       double[][] prev=new double[n][n];
       prev[start_x][start_y]=1;
       for(int k=1;k<=step;k++){
           double[][]curr=new double[n][n];
           for(int i=0;i<n;i++){
               for(int j=0;j<n;j++){
                   for(int[]dir:dirs){
                       int x=i+dir[0];
                       int y=j+dir[1];
                       if(isSafe(x,y,n)){
                           curr[i][j]+=prev[x][y]/8.0;
                       }
                   }
               }
           }
           prev=curr;
       }
       
       double res=0;
       for(int i=0;i<n;i++){
           for(int j=0;j<n;j++){
               res+=prev[i][j];
           }
       }
       return res;
       
    }
}
0
eren08Premium3 days ago
 bool isValid(int ni, int nj, int n)
    {
        return ni >= 0 && ni < n && nj >= 0 && nj < n;
    }
    double findProb(int N, int start_x, int start_y, int steps)
    {
        vector<vector<double>> curr(N, vector<double>(N, 0.0)), next(N,    vector<double>(N, 0.0));
        double ans = 0.0;
        curr[start_x][start_y] = 1.0;
        for (int m = 1; m <= steps; m++)
        {
            for (int i = 0; i < N; i++)
            {
                for (int j = 0; j < N; j++)
                {
                    if (curr[i][j] != 0.0)
                    {
                        int ni = 0, nj = 0;
                        ni = i - 2;
                        nj = j + 1;
                        if (isValid(ni, nj, N))
                            next[ni][nj] += curr[i][j] * 0.125;
                        ni = i - 1;
                        nj = j + 2;
                        if (isValid(ni, nj, N))
                            next[ni][nj] += curr[i][j] * 0.125;
                        ni = i + 1;
                        nj = j + 2;
                        if (isValid(ni, nj, N))
                            next[ni][nj] += curr[i][j] * 0.125;
                        ni = i + 2;
                        nj = j + 1;
                        if (isValid(ni, nj, N))
                            next[ni][nj] += curr[i][j] * 0.125;
                        ni = i - 1;
                        nj = j - 2;
                        if (isValid(ni, nj, N))
                            next[ni][nj] += curr[i][j] * 0.125;
                        ni = i + 1;
                        nj = j - 2;
                        if (isValid(ni, nj, N))
                            next[ni][nj] += curr[i][j] * 0.125;
                        ni = i + 2;
                        nj = j - 1;
                        if (isValid(ni, nj, N))
                            next[ni][nj] += curr[i][j] * 0.125;
                        ni = i - 2;
                        nj = j - 1;
                        if (isValid(ni, nj, N))
                            next[ni][nj] += curr[i][j] * 0.125;
                    }
                }
            }
            curr = next;
            next = vector<vector<double>>(N, vector<double>(N, 0.0));
        }
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            {
                ans += curr[i][j];
            }
        }
        return ans;
    }
+2
kunshmanghwani3 days ago
Easy to understand , using Lru_cache for memoization 
 
from functools import lru_cache
class Solution:
	def findProb(self, n, r, c, k):
	    dir = [(-1,-2),(-2,-1),(-2,1),(-1,2),(1,2),(2,1),(2,-1),(1,-2)]
		@lru_cache(None)
        def solve(x,y,t):
            if not (0<=x<n and 0<=y<n):
                return 0
            if t==0:
                return 1
            ans=0
            for i,j in dir :
                ans+=solve(x+i,y+j,t-1)
            return ans
        
        return solve(r,c,k)/8**k
+3
greatwhite3 days ago
C++ solution
class Solution{
	public:
	double findProb(int N, int x, int y, int steps) {
	    vector<vector<double>> dp(N, vector<double>(N, 0.0));
	    dp[x][y] = 1.0;
	    
	    int X[] = {1, 1, -1, -1, 2, 2, -2, -2};
	    int Y[] = {2, -2, 2, -2, 1, -1, 1, -1};
	    
	    while(steps--) {
	        vector<vector<double>> ndp(N, vector<double>(N, 0.0));
	        for(int x = 0; x < N; x++) for(int y = 0; y < N; y++) {
	            for(int k = 0; k < 8; k++) {
	                int nx = x + X[k];
	                int ny = y + Y[k];
	                
	                if(nx >= 0 && ny >= 0 && nx < N && ny < N) 
	                    ndp[nx][ny] += dp[x][y] / 8;
	            }
	        }
	        
	        dp = ndp;
	    }
	    
	    double ans = 0.0;
	    for(auto it: dp) ans += accumulate(it.begin(), it.end(), 0.0);
	    
	    return ans;
	}
};
+1
sourav1919sharma3 days ago
class Solution{
	public:
	bool isValid(int r, int c, int n){
	    return (r >= 0 and r < n and c >= 0 and c < n);
	}
	
	double findProb(int N,int start_x, int start_y, int steps){
	    vector<vector<double>>curr(N, vector<double>(N, 0.0));
	    curr[start_x][start_y] = 1.0;
	    
	    vector<vector<int>>direction = {{2, 1}, {-2, 1}, {2, -1}, 
	    								{-2, -1}, {1, 2}, {1, -2}, 
	    								 {-1, 2}, {-1, -2}};
	    
	    for(int step = 1; step <= steps; step++){
	        vector<vector<double>>next(N, vector<double>(N, 0.0));
	        for(int i = 0; i < N; i++){
	            for(int j = 0; j < N; j++){
	                
	                if(curr[i][j] != 0){
	                
    	                for(auto it: direction){
    	                    int nextRow = i + it[0];
    	                    int nextCol = j + it[1];
    	                    
    	                    if(isValid(nextRow, nextCol, N)){
    	                        next[nextRow][nextCol] += 
    	                        			curr[i][j] / 8.0;
    	                    }
    	                }
    	                
	                }
	                
	            }
	        }
	        curr = next;
	    }
	    
	    double prob = 0.0;
	    for(int i = 0; i < N; i++){
	        for(int j = 0; j < N; j++){
	            prob += curr[i][j];
	        }
	    }
	    
	    return prob;
	}
};
+2
rajshaurya9883 days ago
C++ Solution. 0.08 secSolution explained visually in YouTube video
double findInBoardCount(int N,int x, int y, int K, vector<vector<vector<double>>>& lookup)
{
    double count = 0;
    if (x >= 0 && x < N && y >= 0 && y < N) //Inside board
    {
        if (lookup[x][y][K] != -1)
            return lookup[x][y][K];
            
        if (K == 0)
            return 1;
        //1
        count += findInBoardCount(N, x-2, y-1, K-1, lookup);
        //2
        count += findInBoardCount(N, x-2, y+1, K-1, lookup);
        //3
        count += findInBoardCount(N, x+2, y-1, K-1, lookup);
        //4
        count += findInBoardCount(N, x+2, y+1, K-1, lookup);
        //5
        count += findInBoardCount(N, x-1, y-2, K-1, lookup);
        //6
        count += findInBoardCount(N, x-1, y+2, K-1, lookup);
        //7
        count += findInBoardCount(N, x+1, y-2, K-1, lookup);
        //8
        count += findInBoardCount(N, x+1, y+2, K-1, lookup);
        lookup[x][y][K] = count;
    }
    return count;
}
0
patildhiren443 days ago
JAVA - 0.23 - Tabulation
boolean isValid(int r, int c, int n) {
        if (r < 0 || r >= n || c < 0 || c >= n) {
            return false;
        }
        return true;
    }

     int[][] direction = {{2, 1}, {-2, 1}, {2, -1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};

    
    public double findProb(int n, int r, int c, int k)
    {
        // Code here
        double[][][]dp = new double[k+1][n][n];
        
        dp[0][r][c] = 1;
        
        for(int step=1; step<=k; step++){
            for(int i=0; i<n; i++){
                for(int j=0; j<n; j++){
                    
                    for(int[]dir : direction){
                        int oldrow = i + dir[0];
                        int oldcol = j + dir[1];
                        
                        if(isValid(oldrow, oldcol, n)){
                            dp[step][i][j] += dp[step-1][oldrow][oldcol]/8.0;
                        }
                    }
                }
            }
        }
        
        double res = 0;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {

                res += dp[k][i][j];
            }
        }

        return res;
    }
0
neeshumaini553 days ago
from functools import lru_cache
class Solution:
	def findProb(self, n, r, c, k):
	    @lru_cache(None)
        def helper(x,y,total):
            if not (0<=x<n and 0<=y<n): return 0
            if total==0: return 1
            res=0
            for addX,addY in [(-1,-2),(-2,-1),(-2,1),(-1,2),(1,2),(2,1),(2,-1),(1,-2)]:
                res+=helper(x+addX,y+addY,total-1)
            return res
        
        return helper(r,c,k)/8**k
0
neeshumaini553 days ago
#f[r][c][steps]= ∑f[r+dr][c+dc][steps−1]/8.0

def findProb(self, N, r, c, K):
	dp = [[0] * N for _ in range(N)]
        dp[r][c] = 1
        for _ in range(K):
            dp2 = [[0] * N for _ in range(N)]
            for r, row in enumerate(dp):
                for c, val in enumerate(row):
                    for dr, dc in ((2,1),(2,-1),(-2,1),(-2,-1),
                                   (1,2),(1,-2),(-1,2),(-1,-2)):
                        if 0 <= r + dr < N and 0 <= c + dc < N:
                            dp2[r+dr][c+dc] += val / 8.0
            dp = dp2

        return sum(map(sum, dp))
+1
sskanojiya165Premium3 days ago
My C++ Solution:
bool isSafe(int x, int y, int n) {
        if(x >= 0 && x < n && y >= 0 && y < n) return true;
        else return false;
    }
    
	double solve(int i , int j, int n, int k, vector<vector<vector<double>>> &dp) {
	    pair<int,int> dir[] = {{-2,-1}, {-2,1}, {-1,-2}, {1, -2}, {2,-1}, {2,1}, {1,2}, {-1,2}};
	    
	    if(k == 0){
            return 1;
        }
        
        if(dp[i][j][k] != -1)
            return dp[i][j][k];
        
        double ans = 0;
        
        for(int d = 0; d < 8; d++) {
            int p = i + dir[d].first;
            int q = j + dir[d].second;
            
            if(isSafe(p,q,n)) {
                ans += (solve(p,q,n,k-1,dp)/8);
            }
        }
        
        dp[i][j][k] = (double)ans;
        
        return (double)dp[i][j][k];
	}
	
	
	double findProb(int n,int x, int y, int steps)
	{
	   vector<vector<vector<double>>> 
	   dp(n, vector<vector<double>>(n, vector<double>(steps+1, -1)));
	   
	   return solve(x, y, n, steps, dp);
	}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.