0
点赞
收藏
分享

微信扫一扫

蓝桥杯python:方格填数

海牙秋天 2022-02-12 阅读 103

题目:在这里插入图片描述
在这里插入图片描述
程序说明:
此题我用了一个耗时较长的程序解决的。 用了一个库from itertools import permutations,返回可迭代对象的所有数学全排列方式,例如在这里插入图片描述
将0到9十个数进行全排列,然后再陆续进行判断连续数字是否相邻

全部代码:

from itertools import permutations

li=[i for i in range(10)]
x=list(permutations(li,10))
count=0
for i in x:
    res=False
    if abs(i[0]-i[4])==1 or abs(i[0]-i[3])==1 or abs(i[0]-i[5])==1 or abs(i[0]-i[1])==1:
        res=True
    if abs(i[1]-i[0])==1 or abs(i[1]-i[2])==1 or abs(i[1]-i[5])==1 or abs(i[1]-i[4])==1 or abs(i[1]-i[6])==1 :
        res=True
    if abs(i[2]-i[1])==1 or abs(i[5]-i[2])==1 or abs(i[2]-i[6])==1 :
        res=True
    if abs(i[3]-i[0])==1 or abs(i[3]-i[4])==1 or abs(i[3]-i[8])==1 or abs(i[3]-i[7])==1 :
        res=True
    if abs(i[4]-i[0])==1 or abs(i[4]-i[3])==1 or abs(i[4]-i[7])==1 or abs(i[8]-i[4])==1 or abs(i[4]-i[9])==1 or abs(i[5]-i[4])==1 or abs(i[4]-i[1])==1:
        res=True
    if abs(i[5]-i[1])==1 or abs(i[5]-i[0])==1 or abs(i[5]-i[4])==1 or abs(i[5]-i[8])==1 or abs(i[5]-i[9])==1 or abs(i[5]-i[6])==1 or abs(i[5]-i[2])==1 :
        res=True
    if abs(i[6]-i[2])==1 or abs(i[6]-i[1])==1 or abs(i[6]-i[5])==1 or abs(i[6]-i[9])==1  :
        res=True
    if abs(i[7]-i[3])==1 or abs(i[7]-i[4])==1 or abs(i[7]-i[8])==1 :
        res=True
    if abs(i[8]-i[3])==1 or abs(i[8]-i[4])==1 or abs(i[8]-i[5])==1 or abs(i[8]-i[7])==1 or abs(i[8]-i[9])==1 :
        res=True
    if abs(i[9]-i[8])==1 or abs(i[9]-i[4])==1 or abs(i[9]-i[5])==1 or abs(i[9]-i[6])==1:
        res=True
    if not flag:
        count+=1
print(count)

>>> 1580
举报

相关推荐

0 条评论