Python解数独-递归法实践

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

github 代码

github代码地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值