Last active
August 4, 2019 00:44
-
-
Save shiracamus/9bad6ade905daa6487e061d96dd99852 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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