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. What is the probability that the Knight remains in the chessboard after taking K steps, with the condition that it can’t enter the board again once it leaves it?
Examples: 
Let's take: 8x8 chessboard, initial position of the knight : (0, 0), number of steps : 1 At each step, the Knight has 8 different positions to choose from. If it starts from (0, 0), after taking one step it will lie inside the board only at 2 out of 8 positions, and will lie outside at other positions. So, the probability is 2/8 = 0.25
Approach:
One thing that we can observe is that at every step the Knight has 8 choices to choose from. Suppose, the Knight has to take k steps and after taking the Kth step the knight reaches (x,y). There are 8 different positions from where the Knight can reach to (x,y) in one step, and they are: (x+1,y+2), (x+2,y+1), (x+2,y-1), (x+1,y-2), (x-1,y-2), (x-2,y-1), (x-2,y+1), (x-1,y+2). 
What if we already knew the probabilities of reaching these 8 positions after K-1 steps? 
Then, the final probability after K steps will simply be equal to the (Σ probability of reaching each of these 8 positions after K-1 steps)/8;
Here we are dividing by 8 because each of these 8 positions has 8 choices and position (x,y) is one of the choices.
For the positions that lie outside the board, we will either take their probabilities as 0 or simply neglect it.
Since we need to keep track of the probabilities at each position for every number of steps, we need Dynamic Programming to solve this problem. 
We are going to take an array dp[x][y][steps] which will store the probability of reaching (x,y) after (steps) number of moves. 
Base case: if the number of steps is 0, then the probability that the Knight will remain inside the board is 1.
Below is the implementation of the above approach: 
C++
| // C++ program to find the probability of the// Knight to remain inside the chessboard after// taking exactly K number of steps#include <bits/stdc++.h>usingnamespacestd;// size of the chessboard#define N 8// direction vector for the Knightintdx[] = { 1, 2, 2, 1, -1, -2, -2, -1 };intdy[] = { 2, 1, -1, -2, -2, -1, 1, 2 };// returns true if the knight is inside the chessboardboolinside(intx, inty){    return(x >= 0 and x < N and y >= 0 and y < N);}// Bottom up approach for finding the probability to// go out of chessboard.doublefindProb(intstart_x, intstart_y, intsteps){    // dp array    doubledp1[N][N][steps + 1];    // for 0 number of steps, each position    // will have probability 1    for(inti = 0; i < N; ++i)        for(intj = 0; j < N; ++j)            dp1[i][j][0] = 1;    // for every number of steps s    for(ints = 1; s <= steps; ++s) {                // for every position (x,y) after        // s number of steps        for(intx = 0; x < N; ++x) {            for(inty = 0; y < N; ++y) {                doubleprob = 0.0;                // for every position reachable from (x,y)                for(inti = 0; i < 8; ++i) {                    intnx = x + dx[i];                    intny = y + dy[i];                    // if this position lie inside the board                    if(inside(nx, ny))                        prob += dp1[nx][ny][s - 1] / 8.0;                }                // store the result                dp1[x][y][s] = prob;            }        }    }    // return the result    returndp1[start_x][start_y][steps];}// Driver Codeintmain(){    // number of steps    intK = 3;    // Function Call    cout << findProb(0, 0, K) << endl;    return0;} | 
Java
| // Java program to find the probability// of the Knight to remain inside the// chessboard after taking exactly K// number of stepsclassGFG {    // size of the chessboard    staticfinalintN = 8;    // direction vector for the Knight    staticintdx[] = { 1, 2, 2, 1, -1, -2, -2, -1};    staticintdy[] = { 2, 1, -1, -2, -2, -1, 1, 2};    // returns true if the knight is    // inside the chessboard    staticbooleaninside(intx, inty)    {        return(x >= 0&& x < N && y >= 0&& y < N);    }    // Bottom up approach for finding    // the probability to go out of    // chessboard.    staticdoublefindProb(intstart_x, intstart_y,                           intsteps)    {        // dp array        doubledp1[][][] = newdouble[N][N][steps + 1];        // for 0 number of steps, each position        // will have probability 1        for(inti = 0; i < N; ++i)            for(intj = 0; j < N; ++j)                dp1[i][j][0] = 1;        // for every number of steps s        for(ints = 1; s <= steps; ++s) {            // for every position (x, y) after            // s number of steps            for(intx = 0; x < N; ++x) {                for(inty = 0; y < N; ++y) {                    doubleprob = 0.0;                    // for every position reachable                    // from (x, y)                    for(inti = 0; i < 8; ++i) {                        intnx = x + dx[i];                        intny = y + dy[i];                        // if this position lie                        // inside the board                        if(inside(nx, ny))                            prob                                += dp1[nx][ny][s - 1] / 8.0;                    }                    // store the result                    dp1[x][y][s] = prob;                }            }        }        // return the result        returndp1[start_x][start_y][steps];    }    // Driver code    publicstaticvoidmain(String[] args)    {        // number of steps        intK = 3;        // Function Call        System.out.println(findProb(0, 0, K));    }}// This code is contributed by Anant Agarwal. | 
Python3
| # Python3 program to find the probability of# the Knight to remain inside the chessboard# after taking exactly K number of steps# size of the chessboardN =8# Direction vector for the Knightdx =[1, 2, 2, 1, -1, -2, -2, -1]dy =[2, 1, -1, -2, -2, -1, 1, 2]# returns true if the knight# is inside the chessboarddefinside(x, y):    return(x >=0andx < N andy >=0andy < N)# Bottom up approach for finding the# probability to go out of chessboard.deffindProb(start_x, start_y, steps):    # dp array    dp1 =[[[0fori inrange(N+5)]             forj inrange(N+5)]            fork inrange(steps +5)]    # For 0 number of steps, each    # position will have probability 1    fori inrange(N):        forj inrange(N):            dp1[i][j][0] =1    # for every number of steps s    fors inrange(1, steps +1):        # for every position (x,y) after        # s number of steps        forx inrange(N):            fory inrange(N):                prob =0.0                # For every position reachable from (x,y)                fori inrange(8):                    nx =x +dx[i]                    ny =y +dy[i]                    # if this position lie inside the board                    if(inside(nx, ny)):                        prob +=dp1[nx][ny][s-1] /8.0                # store the result                dp1[x][y][s] =prob    # return the result    returndp1[start_x][start_y][steps]# Driver code# number of stepsK =3# Function Callprint(findProb(0, 0, K))# This code is contributed by Anant Agarwal. | 
C#
| // C# program to find the// probability of the Knight// to remain inside the// chessboard after taking// exactly K number of stepsusingSystem;classGFG {    // size of the chessboard    staticintN = 8;    // direction vector    // for the Knight    staticint[] dx = { 1, 2, 2, 1, -1, -2, -2, -1 };    staticint[] dy = { 2, 1, -1, -2, -2, -1, 1, 2 };    // returns true if the    // knight is inside the    // chessboard    staticboolinside(intx, inty)    {        return(x >= 0 && x < N && y >= 0 && y < N);    }    // Bottom up approach for    // finding the probability    // to go out of chessboard.    staticdoublefindProb(intstart_x, intstart_y,                           intsteps)    {        // dp array        double[, , ] dp1 = newdouble[N, N, steps+1];        // for 0 number of steps,        // each position will have        // probability 1        for(inti = 0; i < N; ++i)            for(intj = 0; j < N; ++j)                dp1[i, j, 0] = 1;        // for every number        // of steps s        for(ints = 1; s <= steps; ++s) {            // for every position (x, y)            // after s number of steps            for(intx = 0; x < N; ++x) {                for(inty = 0; y < N; ++y) {                    doubleprob = 0.0;                    // for every position                    // reachable from (x, y)                    for(inti = 0; i < 8; ++i) {                        intnx = x + dx[i];                        intny = y + dy[i];                        // if this position lie                        // inside the board                        if(inside(nx, ny))                            prob                                += dp1[nx, ny, s - 1] / 8.0;                    }                    // store the result                    dp1[x, y, s] = prob;                }            }        }        // return the result        returndp1[start_x, start_y, steps];    }    // Driver code    staticvoidMain()    {        // number of steps        intK = 3;        // Function Call        Console.WriteLine(findProb(0, 0, K));    }}// This code is contributed// by Sam007 | 
PHP
| <?php // PHP program to find the probability // of the Knight to remain inside the // chessboard after taking exactly K// number of steps// size of the chessboard$N= 8;// direction vector for the Knight$dx= array(1, 2, 2, 1, -1, -2, -2, -1 );$dy= array(2, 1, -1, -2, -2, -1, 1, 2 );// returns true if the knight is // inside the chessboardfunctioninside($x, $y){    global$N;    return($x>= 0 and$x< $Nand            $y>= 0 and$y< $N);}// Bottom up approach for finding the // probability to go out of chessboard.functionfindProb($start_x, $start_y, $steps){    global$N, $dx, $dy;        // dp array    $dp1= array_fill(0, $N,            array_fill(0, $N,            array_fill(0, $steps+1, NULL)));    // for 0 number of steps, each     // position will have probability 1    for($i= 0; $i< $N; ++$i)        for($j= 0; $j< $N; ++$j)            $dp1[$i][$j][0] = 1;    // for every number of steps s    for($s= 1; $s<= $steps; ++$s)    {        // for every position (x,y) after        // s number of steps        for($x= 0; $x< $N; ++$x)        {            for($y= 0; $y< $N; ++$y)            {                $prob= 0.0;                // for every position                 // reachable from (x,y)                for($i= 0; $i< 8; ++$i)                {                    $nx= $x+ $dx[$i];                    $ny= $y+ $dy[$i];                    // if this position lie inside                    // the board                    if(inside($nx, $ny))                        $prob+= $dp1[$nx][$ny][$s- 1] / 8.0;                }                // store the result                $dp1[$x][$y][$s] = $prob;            }        }    }    // return the result    return$dp1[$start_x][$start_y][$steps];}// Driver Code// number of steps$K= 3;// Function CallechofindProb(0, 0, $K) . "\n";// This code is contributed by ita_c?> | 
Javascript
| <script>// Javascript program to find the probability// of the Knight to remain inside the// chessboard after taking exactly K// number of steps        // size of the chessboard    let N = 8;        // direction vector for the Knight    let dx = [ 1, 2, 2, 1, -1, -2, -2, -1 ];        let dy = [2, 1, -1, -2, -2, -1, 1, 2];        // returns true if the knight is    // inside the chessboard    functioninside(x,y)    {        return(x >= 0 && x < N && y >= 0 && y < N);    }        // Bottom up approach for finding    // the probability to go out of    // chessboard.    functionfindProb(start_x, start_y, steps)    {        // dp array        let dp1 = newArray(N);        for(let i = 0; i < N; i++)        {            dp1[i] = newArray(N);            for(let j = 0; j < N; j++)            {                dp1[i][j] = newArray(steps + 1);                for(let k = 0; k < steps + 1; k++)                {                    dp1[i][j][k] = 0;                }            }        }                // for 0 number of steps, each position        // will have probability 1        for(let i = 0; i < N; ++i)            for(let j = 0; j < N; ++j)                dp1[i][j][0] = 1;                // for every number of steps s        for(let s = 1; s <= steps; ++s)         {             // for every position (x, y) after            // s number of steps            for(let x = 0; x < N; ++x)             {                 for(let y = 0; y < N; ++y)                 {                     let prob = 0.0;                                        // for every position reachable                    // from (x, y)                    for(let i = 0; i < 8; ++i)                    {                        let nx = x + dx[i];                        let ny = y + dy[i];                         // if this position lie                        // inside the board                        if(inside(nx, ny))                            prob                                += dp1[nx][ny][s - 1] / 8.0;                    }                     // store the result                    dp1[x][y][s] = prob;                }            }        }         // return the result        returndp1[start_x][start_y][steps];    }         // Driver code        // number of steps    let K = 3;    // Function Call    document.write(findProb(0, 0, K));        // This code is contributed by rag2127</script> | 
0.125
Time Complexity: O(NxNxKx8) which is O(NxNxK), where N is the size of the board and K is the number of steps. 
Space Complexity: O(NxNxK)
This article is contributed by Avinash Kumar Saw. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







