zoukankan      html  css  js  c++  java
  • 数独

    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()
  • 相关阅读:
    关于Combobox的多选和单选情况
    Struts2的method{1}用法
    ${sessionScope.user}的使用方法
    jQuery 遍历
    jQuery的Event对象(实例)。
    度熊全是由1构成的字符串
    Prime Ring Problem
    八皇后问题
    Hanoi
    全排列
  • 原文地址:https://www.cnblogs.com/fenix/p/2576640.html
Copyright © 2011-2022 走看看