数独:9x9
编了一段代码,就是末尾那里,重复“刷”几次,就排好了。
# -*- coding: utf-8 -*- #coding=utf-8 __author__ = 'bjhhh' ''' 数独 ''' import numpy as np a = np.array([[0,0,1,0,0,0,6,7,9], [2,0,0,0,7,9,1,0,8], [0,0,9,1,3,8,0,0,5], [0,2,3,0,5,6,8,0,7], [4,5,0,0,9,0,0,0,0], [7,0,8,3,0,0,4,0,0], [0,0,0,7,6,0,9,8,4], [0,6,0,0,8,0,7,2,3], [0,3,0,0,2,0,0,0,1] ]) print (a) print("+++"*60) print("============a[]是原始数据,b[]是预估集合数据,c[]是结果") set000 = set("123456789") b = np.zeros([9,9],dtype=set) #b = [[set000 for i in range(9)] for i in range(9)] #b[1][3]={"2","4"} # 把集合中的数字,全部转换为字符串 def set_num2str(arr1): already_set = set(arr1) - set([0]) #把本行已有默认值的数字,去掉0以后,做成一个集合,备用。 already_set = [str(i) for i in already_set] already_set = set(already_set) return already_set # 根据x,y坐标位置,判断是第几宫 def get9gong(x, y): msg = "" if x < 3: if y < 3: tmp = np.ravel(a[0:3, 0:3]) msg="第1宫" elif y < 6: tmp = np.ravel(a[0:3, 3:6]) msg="第2宫" else: tmp = np.ravel(a[0:3, 6:9]) msg="第3宫" elif x < 6: if y < 3: tmp = np.ravel(a[3:6, 0:3]) msg="第4宫" elif y < 6: tmp = np.ravel(a[3:6, 3:6]) msg="第5宫" else: tmp = np.ravel(a[3:6, 6:9]) msg="第6宫" else: if y < 3: tmp = np.ravel(a[6:9, 0:3]) msg="第7宫" elif y < 6: tmp = np.ravel(a[6:9, 3:6]) msg="第8宫" else: tmp = np.ravel(a[6:9, 6:9]) msg="第9宫" #print(msg) return tmp pass # 重复多筛几遍,把集合中多余部分剔除 def reflux(b): # 四、再筛横行 print("+++"*60,"再筛横行") for x in range(9): already_set = set() for y in range(9): if len(b[x][y])==1: already_set.add("".join(b[x][y])) for y in range(9): if len(b[x][y]) > 1: b[x][y] = b[x][y] & (set000- set(already_set)) # print() print("+++"*60,"再筛纵行") # 五、遍历9个纵行 for y in range(9): already_set = set() for x in range(9): if len(b[x][y])==1: already_set.add("".join(b[x][y])) for x in range(9): if len(b[x][y]) > 1: b[x][y] = b[x][y] & (set000- set(already_set)) # 六、遍历9宫 print("+++"*60,"再筛9宫") for x in range(9): for y in range(9): ls9gong = get9gong(x, y) ls9gong = set_num2str(ls9gong) if len(b[x][y])==1: # 当前格子的集合、当前九宫格还没有的集合,取交集 b[x][y] = b[x][y] & (set000- ls9gong) return b pass print("+++"*60,"遍历9个横行") # 一、遍历9个横行 for x in range(9): print("***" * 10, x) ls_x = a[x] already_set = set_num2str(a[x]) for y in range(9): val = ls_x[y] # 从a给b赋值,默认值不是0的赋值。 if val > 0: b[x][y] = set(str(val)) # 从a给b赋值,是0的赋值。(先赋值12345679集合,再去除本行已有的集合) if val == 0: b[x][y] = set000 - already_set print(b) print("+++"*60,"遍历9个纵行") # 二、遍历9个纵行 for y in range(9): print("***" * 10, y) ls_y = a[0:9,y] already_set = set_num2str(ls_y) for x in range(9): val = ls_y[x] # 从a给b赋值,是0的赋值。(先赋值12345679集合,再去除本行已有的集合) if val == 0: b[x][y] = b[x][y] - already_set print(b) # 三、遍历9宫 print("+++"*60,"遍历9宫") for x in range(9): for y in range(9): ls9gong = get9gong(x, y) ls9gong = set_num2str(ls9gong) if a[x][y]==0: # 当前格子的集合、当前九宫格还没有的集合,取交集 b[x][y] = b[x][y] & (set000- ls9gong) # print(b[x][y]) b=reflux(b) b=reflux(b) b=reflux(b) b=reflux(b) print(b)
...