Created
March 7, 2015 09:21
-
-
Save diabloneo/bc30ad458c2834b2f7b0 to your computer and use it in GitHub Desktop.
N Queens Problem -- in recursive method
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
count = 0 | |
def can_place(board, n, row, col): | |
if any([board[i][col] for i in range(row)] | |
+ [board[row-i][col-i] for i in range(1, row+1) if col >= i] | |
+ [board[row-i][col+i] for i in range(1, row+1) if (col+i) < n]): | |
return False | |
return True | |
def queen(board, n, row): | |
global count | |
if row == n: | |
count += 1 | |
return | |
for col in range(n): | |
if can_place(board, n, row, col): | |
board[row][col] = 1 | |
queen(board, n, row+1) | |
board[row][col] = 0 | |
def main(): | |
n = int(raw_input()) | |
board = [[0]*n for i in range(n)] | |
queen(board, n, 0) | |
print count | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment