python写算法题:leetcode: 37. Sudoku Solver

import math
class Solution(object):
    def solveSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        box={}
        box2={}
        for i,line in enumerate(board):
            for j,c in enumerate(line):
                box[(i,j)]=0
                if c!='.':
                    box[(i,j)]=(1<<(int(c)-1))
                else:
                    box2[(i,j)]=(1<<9)-1   
        for loop in xrange(81):
            for i in xrange(0,9):
                for j in xrange(0,9):
                    if box[(i,j)]!=0: continue
                    for i0 in xrange((i/3)*3, (i/3)*3+3):
                        for j0 in xrange((j/3)*3, (j/3)*3+3):
                            box2[(i,j)]&=~box[(i0,j0)]
                    for i0 in xrange(0, 9):
                        box2[(i,j)]&=~box[(i0,j)]
                        box2[(i,j)]&=~box[(i,i0)]
            loop=False        
            for i in xrange(0,9):
                for j in xrange(0,9):
                    if box[(i,j)]!=0:
                        continue
                    loop=True
                    if box2[(i,j)] == 0:
                        return False
                    if (~box2[(i,j)]+1)&box2[(i,j)] == box2[(i,j)]:
                        box[(i,j)]=box2[(i,j)] 
        
        for i in xrange(0,9):
            for j in xrange(0,9):
                if box[(i,j)]>0: board[i][j]=str(int(math.log(box[(i,j)],2))+1)
        return True
                

 

点赞