八皇后问题:在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问一共有多少种摆法。
count = 0
for a in range(8): # 第一个皇后
for b in range(8): # 第二个皇后
if a == b \
or a == b + 1 or a == b - 1: # a == b判断第二个皇后是否与第一个皇后同一列
continue # a == b + 1/a == b - 1判断第二个皇后是否与第一个皇后同一对角线
for c in range(8): # 第三个皇后
if a == c or b == c \
or b == c + 1 or b == c - 1 \
or a == c + 2 or a == c - 2:
continue
for d in range(8): # 第四个皇后
if a == d or b == d or c == d \
or c == d + 1 or c == d - 1 \
or b == d + 2 or b == d - 2 \
or a == d + 3 or a == d - 3:
continue
for e in range(8): # 第五个皇后
if a == e or b == e or c == e or d == e \
or d == e + 1 or d == e - 1 \
or c == e + 2 or c == e - 2 \
or b == e + 3 or b == e - 3 \
or a == e + 4 or a == e - 4:
continue
for f in range(8): # 第六个皇后
if a == f or b == f or c == f or d == f or e == f \
or e == f + 1 or e == f - 1 \
or d == f + 2 or d == f - 2 \
or c == f + 3 or c == f - 3 \
or b == f + 4 or b == f - 4 \
or a == f + 5 or a == f - 5:
continue
for g in range(8): # 第七个皇后
if f == g or a == g or b == g or c == g or d == g or e == g \
or f == g + 1 or f == g - 1 \
or e == g + 2 or e == g - 2 \
or d == g + 3 or d == g - 3 \
or c == g + 4 or c == g - 4 \
or b == g + 5 or b == g - 5 \
or a == g + 6 or a == g - 6:
continue
for h in range(8): # 第八个皇后
if a == h or b == h or c == h or d == h or e == h or f == h or g == h \
or g == h + 1 or g == h - 1 \
or f == h + 2 or f == h - 2 \
or e == h + 3 or e == h - 3 \
or d == h + 4 or d == h - 4 \
or c == h + 5 or c == h - 5 \
or b == h + 6 or b == h - 6 \
or a == h + 7 or a == h - 7:
continue
count += 1
print(f"一共有{count}种摆法")
演示结果: