Program to find the percentage of places where knight can move and not left the board in Python

PythonServer Side ProgrammingProgramming

Suppose we have four values n, x, y, and k. Here n indicates an n x n chessboard and x, y coordinate represents a knight is placed at (x, y). The knight has to take exactly k steps, where at each step it can move any of the 8 directions uniformly at random. We have to find the percentage chance (nearest integer) that the knight remains in the chessboard after taking k moves. We have to follow a condition that it cannot enter the board again once it leaves it.

So, if the input is like n = 8, (x = 0, y = 0), k = 1, then the output will be 50, as here we have 8x8 chessboard and the initial position of the knight is (1, 1). It can take k = 1 step. Taking one step it will lie inside the board only at 4 out of 8 positions, and will lie outside at other positions. So 50%.

To solve this, we will follow these steps −

  • Make a list of moves [(1, 2) ,(1, -2) ,(-1, 2) ,(-1, -2) ,(2, 1) ,(2, -1) ,(-2, 1) ,(-2, -1) ]
  • Define a function dfs() . This will take x, y, k
  • if (x, y) are not in range of the board, then
    • return 0
  • if k is same as 0, then
    • return 1
  • s = empty list
  • for all moves (dx, dy) in moves −
    • x = dfs(x + dx, y + dy, k - 1) / 8
    • insert x into s
  • return sum of the elements in s
  • From the main method do the following −
  • return rounded result of (dfs(x, y, k) * 100) to nearest integer

Let us see the following implementation to get better understanding −

Example

 Live Demo

moves = [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)]
class Solution:
   def solve(self, n, x, y, k):
      def dfs(x, y, k):
         if x < 0 or y < 0 or x >= n or y >= n:
            return 0
         if k == 0:
            return 1
         return sum(dfs(x + dx, y + dy, k - 1) / 8 for dx, dy in moves)
      return int(dfs(x, y, k) * 100)
ob = Solution()
n = 8
x = 1
y = 1
k = 1
print(ob.solve(n, x, y, k))

Input

8, 1, 1, 1

Output

0
raja
Updated on 19-Nov-2020 06:39:14

Advertisements