【Python】9×9数独计算器

游戏规则: 每行每列数字不同,每个九宫格数字不一致,且灰色区域数字不一致!


# 判断每一行数字是否不同
def check_row(arr):
    for i in arr:
        if(len(i) != len(set(i))):
            return False
    return True
# 判断每一列数字不相同
def check_col(arr):
    arrDict = []
    for i in range(len(arr)):
        # 读取每一行的
        for j in range(len(arr[0])):
            arrDict.append(arr[i][j])
        if(len(arrDict) != len(set(arrDict))):
            return False
        else:
            arrDict.clear()
    return True

# 判断每个九宫格不相同
def check_every(arr):
    #找每个九宫格左上角的点
    dict2 = []
    i = 0
    while (i < len(arr)):
        j = 0
        while (j < len(arr)):
            for m in range(i, i + 3):
                for n in range(j, j + 3):
                    tmp = [m, n]
                    dict2.append(tmp)
            j += 3
        i += 3
    n = 9  # 大列表中几个数据组成一个小列表
    dict3 = [dict2[i:i + n] for i in range(0, len(dict2), n)]
    checkTmp = []
    for aa in dict3:
        for mm in aa:
            checkTmp.append(arr[mm[0]][mm[1]])
        if (len(checkTmp) != len(set(checkTmp))):
            return False
        checkTmp.clear()
    return True
# 指定区域数字不相同
def check_appoint(arr):
    points = [[1, 1], [1, 5], [5, 1], [5, 5]]
    dict3 = []
    for i in range(len(points)):
        # 遍历每一个左上角的点
        rowNum = points[i][0]
        colNum = points[i][1]
        dict3.clear()
        for m in range(rowNum, rowNum + 3):
            for n in range(colNum, colNum + 3):
                tmp = [m, n]
                dict3.append(tmp)
        # 读取列表中每个点对应的值
        listTmp = []
        for point in dict3:
            listTmp.append(arr[point[0]][point[1]])
        if (len(listTmp) != len(set(listTmp))):
            return False
    return True

arr = [
    [0,0,0,1,3,8,5,0,0],
    [0,0,0,0,0,4,2,0,0],
    [0,0,0,0,0,0,0,6,3],
    [7,0,0,0,0,0,0,5,8],
    [2,0,0,0,0,0,0,0,4],
    [8,3,0,0,0,0,0,0,2],
    [3,8,0,0,0,0,4,0,0],
    [0,0,9,4,0,0,0,3,0],
    [0,0,6,8,1,3,0,0,0]
]
# arr = [
#     [6,7,2,1,3,8,5,4,9],
#     [9,5,3,7,6,4,2,8,1],
#     [4,1,8,2,5,9,7,6,3],
#     [7,6,4,9,2,1,3,5,8],
#     [2,9,5,3,8,6,1,7,4],
#     [8,3,1,5,4,7,6,9,2],
#     [3,8,7,6,9,2,4,1,5],
#     [1,2,9,4,7,5,8,3,6],
#     [5,4,6,8,1,3,9,2,7]
# ]

# 每一行都是由1-9构成,所以创建一个标准列表
pipList = [0,1,2,3,4,5,6,7,8,9]
# 数独中每一行都有数字,减掉已有的,剩下的为每一行需要填写的数字
needList = []
for i in range(0,len(arr)):
    needList.append(list(set(pipList).difference(set(arr[i]))))

print(needList)
# 开始往每一行数组中填写needList[i],编不下去了!!!




if(check_row(arr) & check_col(arr) & check_every(arr) & check_appoint(arr)):
    print(True)
else:
    print(False)

编不下去了,求指教! 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值