Knight Probability in Chessboard LeetCode solution in Python

1
class Solution:
2
def knightProbability(self, n: int, k: int, row: int, column: int) -> float:
3

4
x_dir = [2, 1, -1, -2, -2, -1, 1, 2]
5
y_dir = [1, 2, 2, 1, -1, -2, -2, -1]
6

7
cache = {}
8

9
def kMoves(i, j, moves):
10
if i >= n or j >= n or i < 0 or j < 0:
11
return 0
12

13
if moves == k:
14
return 1
15

16
if (i, j, moves) in cache:
17
return cache[(i, j, moves)]
18

19
totMoves = 0
20
for ind in range(8):
21
totMoves += kMoves(i + x_dir[ind], j + y_dir[ind], moves + 1) * (1 / 8)
22

23
cache[(i, j, moves)] = totMoves
24
return totMoves
25

26
return kMoves(row, column, 0)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0