Skip to content

Instantly share code, notes, and snippets.

@3rogue
Last active August 29, 2015 14:25
八皇后问题,任意两个皇后都不能处于同一行、同一列或同一斜线上
from itertools import permutations as perm
# (1, 5, 8, 6, 3, 7, 2, 4)表示棋子位置:i.imgbox.com/VHrKYxDG.png
cols = perm(range(1,9)) #所有可能a88=40320
# 保证对角线
def OK(s):
sl = set(r-c for r,c in enumerate(s)) # y=x
bs = set(r+c for r,c in enumerate(s)) # y=-x
return len(sl) == len(bs) == 8
solutions = [c for c in cols if OK(c)]
for i,s in enumerate(solutions,1):
print i,":",s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment