Skip to content

Instantly share code, notes, and snippets.

@vishalg0wda
Created March 28, 2021 11:47
Show Gist options
  • Save vishalg0wda/a24b252c64a7ea170bc544baf4d3d2db to your computer and use it in GitHub Desktop.
Save vishalg0wda/a24b252c64a7ea170bc544baf4d3d2db to your computer and use it in GitHub Desktop.
knight-probability-in-chessboard (BF)
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