Skip to content

Instantly share code, notes, and snippets.

@diabloneo
Created March 7, 2015 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diabloneo/bc30ad458c2834b2f7b0 to your computer and use it in GitHub Desktop.
Save diabloneo/bc30ad458c2834b2f7b0 to your computer and use it in GitHub Desktop.
N Queens Problem -- in recursive method
#!/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