Created
August 4, 2016 04:58
-
-
Save somnathrakshit/5a2ea472e1d67a46ca2ff2705411485a to your computer and use it in GitHub Desktop.
n-Queens Problem
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
BOARD_SIZE = 4 | |
def under_attack(col, queens): | |
left = right = col | |
for r, c in reversed(queens): | |
left, right = left-1, right+1 | |
if c in (left, col, right): | |
return True | |
return False | |
def solve(n): | |
if n == 0: return [[]] | |
smaller_solutions = solve(n-1) | |
return [solution+[(n,i+1)] | |
for i in range(BOARD_SIZE) | |
for solution in smaller_solutions | |
if not under_attack(i+1, solution)] | |
for answer in solve(BOARD_SIZE): print answer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment