• 数独


    class SudokuCal:
        def __init__(self):
            self.str1 = '0' * 81
            self.str2 = '0' * 81
            self.answer = 0
            self.done = False
            self.loop = 0
        def same_row(self,i,j):
            return (i%9==j%9)
        def same_col(self,i,j):
            return (i-j)%9==0
        def same_block(self,i,j):
            return (i%27%9/3==j%27%9/3)
        def print_format(self,a):
            for i in range(9):
                for j in range(9):
                    print '%s' % a[9*i+j]
                print ''

        def r(self,a):
            self.loop += 1
            if(self.answer==1 and self.loop>100000):
                self.done = True
            i = a.find('0')
            if(i==-1):
                self.print_format(a)
                print ''
                self.answer +=1
                if(self.answer==1):
                    self.str1=a
                    print('loop %d' % self.loop)
                elif(self.answer==2):
                    self.str2=a
                    self.done=True
                    return
            excluded_numbers = set()
            for j in range(81):
                if(self.same_row(i,j) or self.same_col(i,j) or self.same_block(i,j)):
                    excluded_numbers.add(a[j])
            for m in '123456789':
                if(m not in excluded_numbers):
                    if(self.done):
                        return
                    self.r(a[:i] + m + a[i+1:])

    a = [8,0,0,0,0,0,0,0,0,
         0,0,3,6,0,0,0,0,0,
         0,7,0,0,9,0,2,0,0,
         0,5,0,0,0,7,0,0,0,
         0,0,0,0,4,5,7,0,0,
         0,0,0,1,0,0,0,3,0,
         0,0,1,0,0,0,0,6,8,
         0,0,8,5,0,0,0,1,0,
         0,9,0,0,0,0,4,0,0]
    b = ''.join([str(i) for i in a ])
    s = SudokuCal()
    s.r(b)
    raw_input()
  • 相关阅读:
    Perl的运算符号字符
    windows xp 使用远程桌面时的关机/重新启动方法
    抵御TCP的洪水
    远程桌面连接中的常见问题 连接上就断开
    批量kill mysql进程
    Linux如何查看硬盘型号和缓存
    Apache Rewrite 规则详解
    nginx 内置变量大全
    大数据量分页存储过程效率测试附代码
    ASP.Net 更新页面输出缓存的几种方法(包括用户控件,iframe,页面缓存等)
  • 原文地址:https://www.cnblogs.com/fenix/p/2576640.html
Copyright © 2020-2023  润新知