LeetCode-37-Sudoku Solver, list转字符串join,回溯


class Solution(object):
    count=0
    ans=[[0 for x in range(9)]for y in range(9)]
    def solveSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        B=[[0 for x in range(9)]for y in range(9)]
        for i in range(9):
            for j in range(9):
                if board[i][j]=='.':continue
                B[i][j]=ord(board[i][j])-ord('0')
        for i in range(9):
            for j in range(9):
                if B[i][j] == 0:
                    flag=self.dfs(B, i, j)
                    if flag:
                        #board=B
                        self.copyBoard(board,B)
                        #print B
                        #print board
                        return
                    break

    def copyBoard(self,board,B):
        for i in range(9):
            for j in range(9):
                B[i][j]=chr(ord("0")+B[i][j])
        for i in range(9):
            board[i]="".join(B[i])



    def dfs(self, B, x, y):
        for num in range(1, 10):
            B[x][y] = num
            if self.judgePoint(B, x, y) == False:
                B[x][y] = 0
                continue
            nextx = x
            nexty = y
            while nextx < 9:
                nexty = nexty + 1
                if nexty == 9:
                    nexty = 0
                    nextx += 1
                    if nextx == 9: return True
                if B[nextx][nexty] == 0:
                    break
            flag=self.dfs(B, nextx, nexty)
            if flag:
                return True
            B[x][y] = 0
        return False

    def judgePoint(self, board, x, y):
        area = 0
        for i in range(9):
            if i!=y and board[x][i]==board[x][y]:return False
            if i!=x and board[i][y]==board[x][y]:return False
            px = x / 3 * 3 + i / 3
            py = y / 3 * 3 + i - i / 3 * 3
            c = board[px][py]
            if c == 0: continue
            num = c
            if area & (1 << num) != 0:
                return False
            area |= 1 << num
        return True


你可能感兴趣的:(Leetcode)