Skip to content

Instantly share code, notes, and snippets.

@gabrielfern
Last active September 26, 2018 00:04
Show Gist options
  • Save gabrielfern/bdf9ac1acb9f63420cf44060e6075493 to your computer and use it in GitHub Desktop.
Save gabrielfern/bdf9ac1acb9f63420cf44060e6075493 to your computer and use it in GitHub Desktop.
Find the number of solutions to a n queen problem
from sys import argv
from itertools import combinations
class Board:
def __init__(self, n):
self.board = [[0]*n for _ in range(n)]
def __repr__(self):
repr = ''
n = len(self)
for i in range(n):
for j in range(n):
repr += str(self[i][j])
if j < n - 1:
repr += ' '
if i < n - 1:
repr += '\n'
return repr
def __len__(self):
return len(self.board)
def __getitem__(self, key):
if key not in range(len(self)):
raise IndexError
return self.board[key]
def success(board):
n = len(board)
for i in range(n):
for j in range(n):
if board[i][j]:
for k in range(n):
if board[k][j] and k != i or board[i][k] and k != j:
return False
for a, b in zip(range(i+1, n), range(j+1, n)):
if board[a][b]: return False
for a, b in zip(range(i+1, n), range(j-1, -1, -1)):
if board[a][b]: return False
for a, b in zip(range(i-1, -1, -1), range(j+1, n)):
if board[a][b]: return False
for a, b in zip(range(i-1, -1, -1), range(j-1, -1, -1)):
if board[a][b]: return False
return True
n = int(argv[1])
count = 0
iter = combinations(range(n**2), n)
for e in iter:
b = Board(n)
for i in range(n):
b[e[i]//n][e[i]%n] = 1
if success(b):
count += 1
print(count)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment