Created
October 17, 2016 18:10
-
-
Save cocodrips/77897b446a87a3090a13817b8cd4641a to your computer and use it in GitHub Desktop.
n-queen
This file contains 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
class QueenN(): | |
def __init__(self): | |
pass | |
def create(self, n): | |
boards = [[-1] * n] | |
for row in range(n): | |
boards = self.add_row(row, n, boards) | |
print n, "Pattern:", len(boards) | |
for board in boards: | |
for col in board: | |
for i in xrange(n): | |
if i == col: | |
print "Q", | |
else: | |
print "_", | |
def add_row(self, row, n, boards): | |
next_boards = [] | |
for board in boards: | |
for col in range(n): | |
array = board[:] | |
if self.is_safe(board, row, col): | |
array[row] = col | |
next_boards.append(array) | |
return next_boards | |
def is_safe(self, board, row, col): | |
# cols | |
if col in board: | |
return False | |
# x | |
for i in range(row): | |
if (i - board[i]) == (row - col): | |
return False | |
if abs(board[i] + i) == (row + col): | |
return False | |
return True | |
if __name__ == '__main__': | |
queen = QueenN() | |
for i in range(3, 9): | |
queen.create(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
3 Pattern: 0
4 Pattern: 2
5 Pattern: 10
6 Pattern: 4
7 Pattern: 40
8 Pattern: 92
[Finished in 0.6s]