Skip to content

Instantly share code, notes, and snippets.

@kldtz
Created March 23, 2024 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kldtz/496a81314601dcf4c32e9e112e0481ca to your computer and use it in GitHub Desktop.
Save kldtz/496a81314601dcf4c32e9e112e0481ca to your computer and use it in GitHub Desktop.
from collections import deque
SIZE = 8
def knight_distance(i: int, j: int) -> list[list[int]]:
board = [[None] * SIZE for _ in range(SIZE)]
q = deque([(i, j, 0)])
while q:
(i, j, d) = q.popleft()
if not 0 <= i < SIZE or not 0 <= j < SIZE or board[i][j] is not None:
continue
board[i][j] = d
q.extend(
(i+two, j+one, d+1) if vertical else (i+one, j+two, d+1)
for one in [1, -1]
for two in [2, -2]
for vertical in [True, False]
)
return board
if __name__ == '__main__':
for row in knight_moves(3,4):
print(" ".join(str(c) for c in row))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment