Created
March 28, 2021 11:47
-
-
Save vishalg0wda/a24b252c64a7ea170bc544baf4d3d2db to your computer and use it in GitHub Desktop.
knight-probability-in-chessboard (BF)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def knightProbability(self, N: int, K: int, r: int, c: int) -> float: | |
grid = [[0] * N for _ in range(N)] | |
# utility to count number of moves given a starting position | |
def recur(r: int, c: int, k: int) -> int: | |
if not (0 <= r < N and 0 <= c < N): | |
return 0 | |
if k == 0: | |
return 1 | |
# try all 8 possible moves | |
return ( | |
recur(r - 2, c + 1, k - 1) | |
+ recur(r - 2, c -1, k - 1) | |
+ recur(r - 1, c + 2, k - 1) | |
+ recur(r - 1, c - 2, k - 1) | |
+ recur(r + 1, c + 2, k - 1) | |
+ recur(r + 1, c - 2, k - 1) | |
+ recur(r + 2, c + 1, k - 1) | |
+ recur(r + 2, c - 1, k - 1) | |
) | |
return recur(r, c, K) / float(8 ** K) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment