Skip to content

Instantly share code, notes, and snippets.

@hughdbrown
Created January 27, 2023 21:12
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 hughdbrown/5c14ec41c30532807afaeba9c16789a8 to your computer and use it in GitHub Desktop.
Save hughdbrown/5c14ec41c30532807afaeba9c16789a8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
from collections import deque
def possible(pos, legal_pos):
r, c = pos
can = {
(r + 2, c - 1), (r + 2, c + 1),
(r + 1, c - 2), (r + 1, c + 2),
(r - 1, c - 2), (r - 1, c + 2),
(r - 2, c - 1), (r - 2, c + 1)
}
return can.intersection(legal_pos)
def print_path(path):
letters = "abcdefgh"
print(" ".join(f"{letters[pos[1]]}{pos[0] + 1}" for pos in path))
def main():
queen_pos = (4, 3)
lower_diag = (1, 0)
upper_diag = (7, 0)
# Squares the queen can visit
illegal_pos = set(
[(queen_pos[0], col) for col in range(8)] +
[(row, queen_pos[1]) for row in range(8)] +
[(lower_diag[0] + i, lower_diag[1] + i) for i in range(7)] +
[(upper_diag[0] - i, upper_diag[1] + i) for i in range(8)]
)
# All the squares
all_squares = {(x, y) for x in range(8) for y in range(8)}
# All the legal squares for knight to visit
legal_pos = all_squares - illegal_pos
visits = sorted(legal_pos, reverse=True)
# Squares visitable from a position
hops = {pos: possible(pos, legal_pos) for pos in legal_pos}
current_square = visits[0]
for square in visits:
queue = deque([[current_square]])
while queue:
path = queue.popleft()
last_pos = path[-1]
if last_pos == square:
print_path(path)
current_square = square
break
else:
for p in hops[last_pos] - set(path):
new_path = path + [p]
queue.append(new_path)
if __name__ == '__main__':
main()
@hughdbrown
Copy link
Author

h8
h8 g6 f8
f8 h7 f6 e8
e8 f6 h7 f8 g6 e7 c8
c8 e7 g6 f8 h7 f6 e8 c7 a6 b8
b8 a6 c7 e8 f6 h7
h7 f6 e8 g7
g7 e8 f6 h7 f8 g6 e7
e7 g6 f8 h7 f6 e8 c7
c7 e8 f6 h7 f8 g6 e7 c8 a7
a7 c8 e7 g6 f8 h7 f6 g4 h6
h6 g4 f6 h7 f8 g6
g6 f8 h7 f6
f6 h7 f8 g6 e7 c8 b6
b6 a4 c3 b1 a3 c2 b4 a6
a6 c7 e8 f6 h7 f8 g6 h4
h4 g6 f8 h7 f6 g4
g4 f2 h3 f4
f4 h3 f2 g4 e3 c2 b4
b4 c2 a3 b1 c3 a4
a4 c3 e2 f4 h3
h3 f4 e2 g3
g3 f1 e3
e3 c2 a3 b1 c3
c3 b1 a3
a3 c2 e3 f1 h2
h2 g4 f2
f2 h3 f4 e2
e2 g3 f1 e3 c2
c2 a3 b1 c3 a4 b2
b2 a4 c3 e2 g1
g1 e2 g3 f1
f1 e3 c2 e1
e1 c2 e3 f1 g3 e2 c1
c1 e2 c3 b1
b1 a3 c2 a1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment