Created
March 28, 2021 21:29
-
-
Save vishalg0wda/83b4d1686253883a1c464e8132a59418 to your computer and use it in GitHub Desktop.
knights_probability - OS
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
class Solution: | |
def knightProbability(self, N: int, K: int, r: int, c: int) -> float: | |
moves = [(-2, 1), (-2, -1), (-1, 2), (-1, -2), (1, 2), (1, -2), (2, 1), (2, -1)] | |
dp0 = [[1] * N for _ in range(N)] | |
to_visit = {(r, c)} | |
count = 0 | |
for _ in range(K): | |
dp1 = [[0] * N for _ in range(N)] | |
new_to_visit = set() | |
for (r, c) in to_visit: | |
for (dr, dc) in moves: | |
nr, nc = r + dr, c + dc | |
if 0 <= nr < N and 0 <= nc < N: | |
dp1[nr][nc] += dp0[r][c] | |
new_to_visit.add((nr, nc)) | |
to_visit = new_to_visit | |
dp0 = dp1 | |
count = sum(map(sum, dp0)) | |
return count / float(8 ** K) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment