Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Place Queens by Rounin
def place(num_placed, rowsandcolumns):
if num_placed >= 8:
return set()
for col in range(ord('a'), ord('a')+8):
if chr(col) in rowsandcolumns:
continue
for row in range(1, 9):
diag1 = 1000+col+row
diag2 = 2000+col-row
if str(row) in rowsandcolumns or diag1 in rowsandcolumns or diag2 in rowsandcolumns:
continue
placed = {chr(col)+str(row)}
attempt = place(num_placed+1, rowsandcolumns.union({chr(col), str(row), diag1, diag2}))
if attempt != set() or num_placed == 7:
return placed.union(attempt)
return set()
def place_queens(placed):
rowsandcolumns = set()
num_placed = len(placed)
for square in placed:
diagonal1 = 1000+ord(square[0])+int(square[1])
diagonal2 = 2000+ord(square[0])-int(square[1])
if square[0] in rowsandcolumns or square[1] in rowsandcolumns or diagonal1 in rowsandcolumns or diagonal2 in rowsandcolumns or num_placed > 8:
return set()
rowsandcolumns.add(square[0])
rowsandcolumns.add(square[1])
rowsandcolumns.add(diagonal1)
rowsandcolumns.add(diagonal2)
placed = placed.union(place(num_placed, rowsandcolumns))
return (placed if len(placed) == 8 else set())
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
from itertools import combinations
COLS = "abcdefgh"
ROWS = "12345678"
THREATS = {c + r: set(
[c + ROWS[k] for k in range(8)] +
[COLS[k] + r for k in range(8)] +
[COLS[k] + ROWS[i - j + k] for k in range(8) if 0 <= i - j + k < 8] +
[COLS[k] + ROWS[- k + i + j] for k in range(8) if 0 <= - k + i + j < 8])
for i, r in enumerate(ROWS) for j, c in enumerate(COLS)}
def check_coordinate(coor):
c, r = coor
return c in COLS and r in ROWS
def checker(func, placed, is_possible):
user_set = func(placed.copy())
if not all(isinstance(c, str) and len(c) == 2 and check_coordinate(c) for c in user_set):
print("Wrong Coordinates")
return False
threats = []
for f, s in combinations(user_set.union(placed), 2):
if s in THREATS[f]:
threats.append([f, s])
if not is_possible:
if user_set:
print("Hm, how did you place them?")
return False
else:
return True
if not all(p in user_set for p in placed):
print("You forgot about placed queens.")
return False
if is_possible and threats:
print("I see some problems in this placement.")
return False
return True
assert checker(place_queens, {"b2", "c4", "d6", "e8"}, True), "1st Example"
assert checker(place_queens, {"b2", "c4", "d6", "e8", "a7", "g5"}, False), "2nd Example"
Oct. 11, 2017