Created
May 18, 2015 19:24
-
-
Save lykkin/2c514c3440262243c420 to your computer and use it in GitHub Desktop.
n queens
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 output_board(board): | |
for row in board: | |
print ' '.join(map(str, row)) | |
def place_queen(board, coordinate): | |
new_board = [] | |
for row in board: | |
new_board.append(row[:]) | |
x,y = coordinate | |
for c in range(len(new_board)): | |
new_board[x][c] = 1 | |
new_board[c][y] = 1 | |
dx, dy = x,y | |
while not dx == 0 and not dy == 0: | |
dx, dy = dx - 1, dy - 1 | |
while dx < len(new_board) and dy < len(new_board): | |
new_board[dx][dy] = 1 | |
dx, dy = dx + 1, dy + 1 | |
dx, dy = x,y | |
while dy != 0 and dx != len(new_board) - 1: | |
dx, dy = dx + 1, dy - 1 | |
while dx > 0 and dy < len(new_board): | |
new_board[dx][dy] = 1 | |
dx, dy = dx - 1, dy + 1 | |
return new_board | |
def produce_board(n): | |
res = [] | |
for _ in range(n): | |
res.append([0]*n) | |
return res | |
def n_queens(board, x): | |
output_board(board) | |
n = len(board) | |
if n - 1 == x: | |
return sum(map(lambda x: 1 if x == 0 else 0, board[x])) | |
s = 0 | |
for y in range(n): | |
if board[x][y] == 0: | |
s += n_queens(place_queen(board, (x,y)), x+1) | |
return s | |
print n_queens(produce_board(8), 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment