You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
3.2 KiB

# -*- encoding: utf-8 -*-
'''
@File : data.py
@License : (C)Copyright 2018-2022
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
2022/12/22 9:35 zart20 1.0 None
'''
import numpy as np
import random
from collections import Counter
def Init():
# 构建9*9数组
martix = np.zeros((9, 9), dtype='i1') # 初始化9*9数组并赋值0
for row in range(0, 9):
for col in range(0, 9):
value = random.randint(0,9)
martix[row, col] = value # 给9*9数组martix随机赋值
return martix
def Judge(martix):
# 计算整个数组是否符合要求
for row in range(0, 9):
for col in range(0, 9):
if martix[row][col] == 0:
continue
x, y = row // 3, col // 3 # [x, y] 为宫位置, 即九个小格子为一个宫
row_martix = martix[row, :] # [row, col] 所在行的数字数组
row_set = set(row_martix) # [row, col] 所在行的数字集合
col_martix = martix[:, col] # [row, col] 所在列的数字数组
col_set = set(col_martix) # [row, col] 所在列的数字集合
block_martix = martix[x * 3: x * 3 + 3, y * 3: y * 3 + 3].reshape(9) # [row, col] 所在的宫的数字数组
block_set = set(block_martix) # [row, col] 所在的宫的数字集合
if len(row_martix) != (len(row_set) + Counter(row_martix)[0]) or len(col_martix) != \
(len(col_set) + Counter(col_martix)[0]) or len(block_martix) != (
len(block_set) + Counter(block_martix)[0]):
return False
return True
def GetPossible(martix, row, col):
# 获取一个格子里可能可以填的值
Nums = {1, 2, 3, 4, 5, 6, 7, 8, 9}
x, y = row // 3, col // 3
rowSet = set(martix[row, :]) # [row, col] 所在行的数字集合
colSet = set(martix[:, col]) # [row, col] 所在列的数字集合
blockSet = set(martix[x * 3: x * 3 + 3, y * 3: y * 3 + 3].reshape(9)) # [row, col] 所在宫的数字集合
return Nums - rowSet - colSet - blockSet
def Solve(martix):
"""求解数组"""
for row in range(9):
for col in range(9):
if martix[row, col] == 0:
possible = GetPossible(martix, row, col) # 所有的可能的数字
for value in possible:
martix[row, col] = value # 将可能的数组填入
if Solve(martix): # 继续深度优先遍历填入数字
return True # 填完最后一个数字
martix[row, col] = 0 # 如果当前填入的数字会导致后面无解则依然填入0表示空白待填
return False
# 当所有的数字填完,数独求解完毕
return True
def InitMartix():
"""创建一个符合要求的带空数组"""
martix = np.zeros((9, 9), dtype='i1')
martix[0][0] = 1 # 手动设置一个初始值
martix[0][3] = 2
martix[3][3] = 1
martix[6][6] = 1
Solve(martix) # 求解整个数独
for i in range(9):
for j in range(9):
if i == j:
martix[i][j] = 0
return martix