python数独代码(DFS,包含剪枝操作)

class Solution:
    def solveSudoku(self, board):
        tmpList = self.todoList(board)
        self.dfs(tmpList, board, 0)

    def dfs(self, tmpList,board, k):
        # 确认完成操作
        if k==len(tmpList):
            return True
        px,py = tmpList[k]
        numBoard = self.nextNum(board,px,py)
        if not numBoard:
            return False
        pp = True
        for i in numBoard:
            board[px][py] = i
            pp = self.dfs(tmpList,board,k+1)
            if pp:      # 少了这一部分,则会导致回溯出错
                return True
        if not pp:      # 如果跳出上述循环,则说明numBoard的候选值均不对,返回上一层
            board[px][py] = '.'

# 获得输入数独矩阵需要填写的位置
    def todoList(self, board):
        tmpList = []
        for i in range(9):
            for j in range(9):
                if (board[i][j]=='.'):
                    tmpList.append((i,j))
        return tmpList

# 对于任意的待填写位置,获得可能的数字候选项,完成剪枝操作(如果没有,则返回空)
    def nextNum(self, board,px,py):
        numTable = ['1','2','3','4','5','6','7','8','9']
        nrow = px//3
        ncol = py//3
        for i in range(9):
            if (i!=px and board[i][py] in numTable):
                numTable.remove(board[i][py])
        for j in range(9):
            if (j!=py and board[px][j] in numTable):
                numTable.remove(board[px][j])     
        for i in range(3):
            for j in range(3):
                tmpx = nrow*3+i
                tmpy = ncol*3+j
                if (tmpx!=px and tmpy!=py and board[tmpx][tmpy] in numTable):
                    numTable.remove(board[tmpx][tmpy])  
        return numTable     

def main():
    board = ['53..7....','6..195...','.98....6.','8...6...3','4..8.3..1','7...2...6','.6....28.','...419..5','....8..79'] 
    # board = ['..53.....','8......2.','.7..1.5..','4....53..','.1..7...6','..32...8.','.6.5....9','..4....3.','.....97..']
    # board = ['.......6.','.....47.5','5.....1.4','1....24..','..8.7....','.3.6.....','2....9..1','..6.8....','.7.3.....']  

    # 将输入的字符串列表转换为二维字符列表,方便后续更改列表内的值
    newBoard = []
    for i in board:
        newBoard.append(list(i))
    t = Solution()
    t.solveSudoku(newBoard)
    print(newBoard)

if __name__ == '__main__':
    main()

你可能感兴趣的:(编程)