Python解数独-递归法实践
数独题目:
000000000
000000012
003045000
000000036
000000400
570008000
000100000
000900020
706000500
求解思路
1.边算边检查
2.先算容易算的点
3.递归法求所有解
定义节点类
class Node(object):
def __init__(self):
self.parent = None
self.children = []
self.question=None
self.state =None
def add_child(self, node):
self.children.append(node)
node.parent = self
def __repr__(self):
pass
return "Node: {}, Q: {}, children:{}, state:\n {}".format(
hash(self), self.question, self.children,self.state)
计算任意空点位置的非可行解
def check(x,y,s):
p=''
for i in range(9):
p+=s[i][y]+s[x][i]
l,m=x//3,y//3
l,m=l*3,m*3
#print(l,m)
for i in range(3):
for j in range(3):
p+=s[l+i][m+j]
return set(p.replace('0',''))
获取需要填的所有点
d=[]
for i in range(9):
for j in range(9):
if S[i][j]=='0':
d.append((i,j))
从任意节点开始探索
def expand(node):
if len(node.question)>0:
current_node=node
q=eva(current_node.question,current_node.state)#先算最好算的点(可能性最低的点)
x,y=q[0],q[1]
print(x,y)
p=a-check(x,y,current_node.state)
for i in list(p):
n=Node()
n.state=copy.deepcopy(current_node.state)
n.question=copy.deepcopy(current_node.question)
n.state[x][y]=i
n.question.remove((x,y))
current_node.add_child(n)
for i in current_node.children:
current_node=i
expand(current_node)
else:
print(node.state)
print('Done!')
效果
解这个 64空的9x9数独,用时约5.9s (单核CPU core i5)
000000000
000000012
003045000
000000036
000000400
570008000
000100000
000900020
706000500