Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Last active August 4, 2019 00:44
Show Gist options
  • Save shiracamus/9bad6ade905daa6487e061d96dd99852 to your computer and use it in GitHub Desktop.
Save shiracamus/9bad6ade905daa6487e061d96dd99852 to your computer and use it in GitHub Desktop.
def n_queen(n):
count = 0
for board in put_queens(board=[None]*n):
for queen in board:
print(''.join('.Q'[x == queen] for x in range(n)))
print()
count += 1
print(count, 'ways')
def put_queens(board, y=0):
n = len(board)
if y == n:
yield board
else:
for x in range(n):
if not conflict(board, x, y):
board[y] = x
yield from put_queens(board, y + 1)
def conflict(board, x, y):
return any(tx == x or tx - ty + y == x or tx + ty - y == x
for ty, tx in enumerate(board[:y]))
if __name__ == '__main__':
n_queen(int(input('n? ')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment