Skip to content

Instantly share code, notes, and snippets.

@adampalay
Created August 17, 2018 19:36
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 adampalay/e9c36302dc061998c30b8237758740bf to your computer and use it in GitHub Desktop.
Save adampalay/e9c36302dc061998c30b8237758740bf to your computer and use it in GitHub Desktop.
8 queens problem in python
def n_queens(N, rows = None, arrangements = None):
if rows is None:
rows = N
if arrangements is None:
arrangements = []
if rows == 0:
return arrangements
if rows == N:
arrangements = [[]]
new_arrangements = []
for col in range(N):
cell = N - rows, col
# if `arrangements` is empty, then this list comprehension is also empty.
# that's a problem for starting out the list of possible arrangements.
# We therefore do a hack in L12 in order to populate the first row of
# the board
new_arrangements += [[cell] + arrangement for arrangement in arrangements
if no_conflict(cell, arrangement)]
return n_queens(N, rows - 1, new_arrangements)
def no_conflict(cell, arrangement):
for position in arrangement:
if position[0] == cell[0] or position[1] == cell[1]:
return False
if abs(position[0] - cell[0]) == abs(position[1] - cell[1]):
return False
return True
if __name__ == '__main__':
print(n_queens(0))
print(n_queens(1))
print(n_queens(2))
print(n_queens(3))
print(n_queens(4))
print(len(n_queens(8)))
for i in range(10):
assert(all(len(arrangement) == i for arrangement in n_queens(i)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment