Created
October 27, 2012 15:50
-
-
Save clippit/3965133 to your computer and use it in GitHub Desktop.
solve n-queens puzzle using python generator
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
#!/usr/bin/env python | |
def next_col(current, n=8): | |
length = len(current) | |
if length == n: | |
return | |
dangerous = current + [item for l in [(val + length - i, val - length + i) for i, val in enumerate(current)] for item in l if item >= 0 and item <= n] | |
for i in range(n): | |
if i not in dangerous: | |
yield i | |
def queens(n=8, columns=[]): | |
if len(columns) == n: | |
yield columns | |
for i in next_col(columns, n): | |
appended = columns + [i] | |
for c in queens(n, appended): | |
yield c | |
if __name__ == '__main__': | |
for solution in queens(8): | |
print solution |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment