Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Place Queens by Moff
class Field(object):
rows = '12345678'
cols = 'abcdefgh'
def __init__(self):
self.layout = None
@classmethod
def possibles(cls, queen):
qc, qr = (a.index(b) for a, b in zip((cls.cols, cls.rows), queen))
result = set()
for i in range(8):
for dr, dc in ((i, i), (-i, -i), (i, -i), (-i, i),
(0, i), (0, -i), (i, 0), (-i, 0)):
col, row = qc + dc, qr + dr
if 0 <= row < 8 and 0 <= col < 8:
result.add(cls.cols[col] + cls.rows[row])
return result
def find_layout(self, queens, awailable):
if len(queens) == 8:
self.layout = queens
if self.layout is not None:
return
for q in awailable:
danger = self.possibles(q)
if all(queen not in danger for queen in queens):
self.find_layout(queens.union({q}), awailable - danger)
def place_queens(queens):
f = Field()
available = set(col+row for row in Field.rows for col in Field.cols)
for q in queens:
if q not in available:
return set()
available -= Field.possibles(q)
f.find_layout(queens, available)
if f.layout is None:
return set()
else:
return f.layout
Aug. 17, 2015