Files
notes/CS1032/lecture-2023-11-23/nqueens.py
bluepython508 dc42625cf1 .
2024-01-22 10:56:12 +00:00

19 lines
514 B
Python

def safe(q1, q2):
(q1x, q1y) = q1
(q2x, q2y) = q2
return q1x != q2x and q1y != q2y and abs(q1x - q2x) != abs(q1y - q2y)
def possible_positions(current, n):
return ((*current, y) for y in range(n) if all(safe((len(current), y), q) for q in enumerate(current)))
def solutions_r(current, n = 8):
if len(current) == n:
yield current
return
for pos in possible_positions(current, n):
yield from solutions_r(pos, n)
def solutions(n = 8):
return solutions_r((), n)